Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

javascript - Selenium WebDriver find object text. Errors out with The result of the xpath expression is: [object Text]. It should be an element

I'm using Selenium to verify the presence of certain text in a web page. This is how the html looks like.

<html>
<div class="a-content">
 <!--!-->==$0
 "
        Text to Find"
 <br>
 <br>
 "
        Second Text to find"
 <br>
</div>

The only way I have been able to identify this text is through xpath.

//div[contains(@class, 'a-content')]//br[1]/preceding-sibling::text()[1] 

I'm not able to use the regular way of identifying this element at it returns an object Text instead of an element.

var x = webDriver.FindElement(By.XPath("//div[contains(@class, 'a-content')]//br[1]/preceding-sibling::text()")).Text;

This is the error I get:

OpenQA.Selenium.InvalidSelectorException : invalid selector: The result of the xpath expression "//div[contains(@class, 'a-content')]//br[1]/preceding-sibling::text()" is: [object Text]. It should be an element.

Alternately, I have tried using JavaScript Executer for finding this text object. But when I run below code it returns null.

IJavaScriptExecutor javascriptExecutor = (IJavaScriptExecutor)webDriver;
String value = (String)javascriptExecutor.ExecuteScript("document.evaluate("//div[contains(@class, 'a-content')]//br[1]/preceding-sibling::text()[1]") ; ");

Any help on this is appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should be able to take out the "::text()" to get the web element (and then get the Text property):

var x = webDriver.FindElement(By.XPath("//div[contains(@class, 'a-content')]//br[1]/preceding-sibling")).Text;

adding the ::text() is returning the text of the element you selected. This is a feature of xapth that doesn't fit into the WebElement expectation of findElement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...