Home > OS >  Selenium Java, how to get second text that wrapped double quotes?
Selenium Java, how to get second text that wrapped double quotes?

Time:09-29

I got this web page to test whether this element contains a certain keyword in it.

<div>
"&nbsp;"
"Network interface updated successfully"
</div>

This is the HTML code and the xpath I am trying to get is

//div[contains(text(),'interface')]

But this xpath doesn't find this element at all. So I tried different way to figure out how it works.

//div/text()[2]

This xpath matches up the element, but it is not the best practice for me.

I attached the screen shot what I am suffering..... enter image description here

CodePudding user response:

if you are so sure about 2nd element has the text. please use following code.

List<WebElement> rows = driver.findElements(By.xpath("your xpath"));
String secondTxt = rows.get(1).getText();

element index startswith 0, so following are the matching 0th element contains 1st text 1st element contains 2nd text

if text index is changing on each runtime, you should not get text based on index. you should iterate every element and get the text.

CodePudding user response:

I Found Something similar to your example here enter image description here

now if you want the entire text enclosed within that element and you dont want to index through the scripts you can do it via java script executor enter image description here

run the below statement with java script executor and it will return the entire text, once you fetch the text you can assert if it contains the expected text.

'return $x("//div[@class='jconfirm-content']//div//div")[0].textContent'

CodePudding user response:

Those are not plain text instead they are text node. If you apply /text() selenium will throw an error, cause it is not supported by Selenium, Please use JavascriptExecutor

Code :

WebElement e = driver.findElement(By.xpath("//span[contains(@class, 'jconfirm-content')]//child::div[1]"));
String el = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].childNodes[1].textContent;", e);
System.out.println(el);
  • Related