简体   繁体   English

如何查找-为2标签标签之间的文本编写xpath

[英]How to find - write xpath for Text Between 2 Label Tag

I am need to find the xpath to get value 300 from the below html page. 我需要从下面的html页面中找到xpath以获得值300。 I have used xpath as //label[contains (text(),'of')]/following-sibling::text() - from stackoverflow answers - but it didn't work out well. 我已经使用xpath作为// label [包含(text(),'of')] / following-sibling :: text()-来自stackoverflow的答案-但效果不佳。 my next action is based on this value. 我的下一个动作就是基于此值。 So I need to read it. 所以我需要阅读它。

<td class="clsLineCounterLabel">
<input id="lineCounter" class="clsLineCounter" tabindex="-1" size="4" value="0" readonly=""/>
<label id="lblOf" for="Of">of</label>
        300 
<label id="lblAllowedTextLines" for="AllowedTextLines">allowed text lines</label>
</td>

Any help ? 有帮助吗?

The text 300 belongs to the <td> tag. 文本300属于<td>标签。 Try 尝试

String value = driver.findElement(By.className("clsLineCounterLabel")).getText();

value will be 300 . value将是300

And the xpath is xpath是

//td[@class='clsLineCounterLabel']

Use below code: 使用以下代码:

String value = driver.findElement(By.xpath("//input[@id='lineCounter]/parent::td")).getText();

Print value on console it will print you whole text of td, then filter integer value. 在控制台上打印值,它将打印您td的整个文本,然后过滤整数值。

Hope this will work. 希望这会奏效。

Thanks Sadik 谢谢Sadik

Getting the 300 is kind of tricky since it doesn't have its own node. 获取300有点棘手,因为它没有自己的节点。

You could get the 300 with some JavaScript with the element as argument: 你可以使用一些带有元素的JavaScript作为参数得到300:

WebElement element = driver.findElement(By.id("lblOf"));
String txt = ((JavascriptExecutor)driver).executeScript(
  "return arguments[0].firstChild.textContent;", element);

Or with a single JavaScript call: 或通过一个JavaScript调用:

String txt = ((JavascriptExecutor)driver).executeScript(
  "return document.getElementById('lblOf').firstChild.textContent;", element);

Or by extracting the number with a regex: 或使用正则表达式提取数字:

String txt = driver.findElement(By.xpath("//*[@id='lblOf']/.."))
                   .getText().replaceAll("[^\\d]", "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM