简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM