Helping Hands
Helping Hands

Reputation: 5396

How to extract text from text nodes through Selenium?

I do have one HTML code from where I want to get text but almost texts are not within any HTML tags.

Html

<div class="div-estro">
    <b class="">Your</b> 
    <b class="">ID:</b>&nbsp;3915 
    <b class="">Time Limit:</b>&nbsp;00:19:56 
    <b class="">IP:</b>&nbsp;123.101.59.87 
    <b class="">Membership Period:</b>&nbsp;8 year <br>
    <b class="">CountryID:</b> 78 
    <b class="">Country:</b> US 
    <b class="">State:</b> OH 
    <b class="">City:</b> Akron 
    <b class="">Status:</b> Available 
    <b class="">Maximum Queue:</b> 4 
    <b class=""><br>CountryProxy:</b> 201.250.101.84:3372 
    <b class="">CountryIP:</b> 59.243.44.192 
</div>

I want to get the text from CountryIP and CountryProxy.

Expecting gettext string : 201.250.101.84:3372

Expecting gettext string:59.243.44.192

I tried xpaths :

//div[@class='div-estro']//text()[12]

//div[@class='div-estro']//text()[13]

Above xpaths seems good when I evaluate using firebug. But when trying to get text using selenium, I am getting the exception.

Upvotes: 2

Views: 2227

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193298

As per the HTML you have shared it's a text node which contains the text 59.243.44.192 so to extract it you can use the following solution:

WebElement myElement = driver.findElement(By.xpath("//div[@class='div-estro']"));
String myCountryIP = ((JavascriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", myElement).toString();

Update:

As per your comment update it's a text node which contains the text 201.250.101.84:3372 so to extract it you can use the following solution:

WebElement myElement = driver.findElement(By.xpath("//div[@class='div-estro']"));
String myCountryProxy = ((JavascriptExecutor)driver).executeScript("return arguments[0].childNodes[24].textContent;", myElement).toString();

Upvotes: 1

Andersson
Andersson

Reputation: 52685

You can use XPath to get required text nodes as below:

String countryProxy = ((JavascriptExecutor)driver).executeScript("return document.evaluate(\"//div[@class='div-estro']/b[.='CountryProxy:']/following-sibling::text()\", document, null, XPathResult.ANY_TYPE, null).iterateNext().textContent;").toString();
String countryIP = ((JavascriptExecutor)driver).executeScript("return document.evaluate(\"//div[@class='div-estro']/b[.='CountryIP:']/following-sibling::text()\", document, null, XPathResult.ANY_TYPE, null).iterateNext().textContent;").toString();

Just update predicate for preceding b node to get required text:

b[.='State:']
b[.='Membership Period:']
...

Upvotes: 1

Related Questions