我确实有一个 HTML 代码,我想从其中获取文本,但几乎文本不在任何 HTML 标记内。
HTML
<div class="div-estro">
<b class="">Your</b>
<b class="">ID:</b> 3915
<b class="">Time Limit:</b> 00:19:56
<b class="">IP:</b> 123.101.59.87
<b class="">Membership Period:</b> 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>
我想从 CountryIP 和 CountryProxy 获取文本。
需要 gettext 字符串:201.250.101.84:3372
需要 gettext 字符串:59.243.44.192
我尝试过 xpath:
//div[@class='div-estro']//text()[12]
//div[@class='div-estro']//text()[13]
当我使用 firebug 进行评估时,上面的 xpaths 看起来不错。但是当尝试使用 selenium 获取文本时,我遇到了异常。
最佳答案
根据您共享的 HTML,它是一个文本节点,其中包含文本 59.243.44.192,因此要提取它,您可以使用以下解决方案:
WebElement myElement = driver.findElement(By.xpath("//div[@class='div-estro']"));
String myCountryIP = ((JavascriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", myElement).toString();
更新:
根据您的评论更新,它是一个文本节点,其中包含文本 201.250.101.84:3372,因此要提取它,您可以使用以下解决方案:
WebElement myElement = driver.findElement(By.xpath("//div[@class='div-estro']"));
String myCountryProxy = ((JavascriptExecutor)driver).executeScript("return arguments[0].childNodes[24].textContent;", myElement).toString();
关于java - 如何通过Selenium从文本节点中提取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52215293/