我试图仅从子元素获取文本。如下所示:
<strong class="EnvMain">
<strong id="currentClock">11:19</strong>
GMT
</strong>我只想得到GMT文本。
我尝试过像这样编写xpath:.//*[@id='userEnvironmentInfo']/div[2]/a/strong/text()],但是这样就找不到元素了。
提前谢谢。
HTML的更新:
<div class="DateTime">
<a class="EnvPicker" title="Change your timezone" href="javascript:void(0);">
<span class="EnvDD">▾</span>
<span class="EnvIcon DateTimeIcon">The time is:</span>
<strong class="EnvMain">
<strong id="currentClock">17:34</strong>
GMT
</strong>
<span id="currentDay" class="EnvMore">Monday</span>
<span id="currentDate" class="EnvMore">14.04.2014</span>
</a>
<div class="EnvContainer">
<ol id="timeZoneOptions" class="EnvList">
<li class="EnvItem">
<a class="EnvOption" title="Set the timezone to GMT-12" onclick="return false;" rel="-12" href="javascript:void(0);">
<strong class="EnvMain">GMT-12</strong>
<span class="EnvMore">Current time:01:25</span>
</a>
</li>
<li class="EnvItem">
<a class="EnvOption" title="Set the timezone to GMT-11" onclick="return false;" rel="-11" href="javascript:void(0);">在这里,这些元素将一直持续到GMT +12。
发布于 2014-04-14 21:37:04
您要搜索的xpath是:
//strong[@class='EnvMain']/text()此xpath返回文本,而不是web元素。
如果您想使用selenium + java获取文本,您可以尝试以下方法:
driver.findElement(By.xpath("//strong[@class='EnvMain']")).getText();似乎getText函数不会只返回GMT。但我们可以在获得文本后解析如下字符串:
String s = driver.findElement(By.xpath("//strong[@class='EnvMain']/strong[id='currentClock']/..")).getText();
s = s.substring(s.lastIndexOf(' ') + 1);发布于 2014-04-14 22:35:49
使用以下xpath查找该元素:
//strong[@class='EnvMain']/strong[@id='currentClock']/..此xpath的作用是查找具有类EnvMain的<strong>元素,该元素有一个id为currentClock的子<strong>。(末尾的..沿dom返回到父元素)。
然后使用getText()方法提取文本:
String gmt = driver
.getElement(By.xpath("//strong[@class='EnvMain']/strong[id='currentClock']/.."))
.getText();然后,如果您想忽略内部<strong>元素中的文本而只获取时区("GMT")...使用xpath没有一个很好的方法来做到这一点。您必须在Java中使用正则表达式来删除不需要的部分:
gmt = gmt.replaceAll("[\\d][\\d]?:[\\d][\\d]\\s*", "");发布于 2016-04-13 19:40:07
在本例中,getText()返回null,因为在列表项中有锚标记,然后锚tag.So的文本使用getAttribute("innerHTML")。但您将无法选择列表中的项目。
WebElement e1 = driver.findElement(By.xpath("//ul[@class='EnvContainer']"));
List<WebElement> list = e1.findElements(By.tagName("li"));
for(WebElement item: list)
{
String s = item.getAttribute("innerHTML");
System.out.println(item.getAttribute("innerHTML"));
}https://stackoverflow.com/questions/23058789
复制相似问题