htmlselenium-webdriverxpath

How to retrieve [object Text] via XPath?


I am working on selenium and trying to access text from a node but I'm not sure how to fetch and assert a text that has keyword approved.

This is the node -

<div class="Notification-body">
    <div class="">
        <div class="type--primary u-textBreak">
            <span class="u-inline">
                <span class="type--title">User Name</span> approved "Page_For_Submission"
            </span>
        </div>
        <span class="u-displayBlock type--note">4 hours ago</span>
    </div>
</div>

Initially I tried this XPath but it is giving no result -

(//span[contains(@class,'title')]/following-sibling::text()[contains(text(),'approved')])[1]

means this is not a simple text node.

Later I used following XPaths and able to locate position of the element

(//html/body/div[7]/div[3]/div[2]/div/div/div/div/ul/li[2]/a/div/div/div/div/span/text())[2]
//span[contains(@class,'title')]/following-sibling::text()
(//span[contains(@class,'title')]/following-sibling::text()[contains(.,'approved')])[1]

But by using these XPaths in selenium

System.out.println(driver.findElement(By.xpath(prop.getProperty("txt_approvedNotification"))).getText());

Getting following error while executing

org.openqa.selenium.InvalidSelectorException: invalid selector: The result of the xpath expression "(XPath of Element)[2]" is: [object Text]. It should be an element.
  (Session info: chrome=77.0.3865.90)
Build info: version: '3.11.0', revision: 'e59cfb3', time: '2018-03-11T20:26:55.152Z'
System info: host: '*****', ip: '*****', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_191'

Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 77.0.3865.90,

Just want to know if its XPath issue or seleniumdriver limitation.


Solution

  • Selenium cannot wrap a single particular text node into WebElement. So as the soultion you can prepare and execute JavaScript code that would find the textnode you require, wrap it into a tag and add to the DOM with some unique ID. Then you'll be able to ontain that element with Selenium (findElement(By.id())).

    Find some details here https://sqa.stackexchange.com/a/33097/27679