简体   繁体   English

如何在 Selenium 上使用 XPath 定位文本上的元素?

[英]How to locate element on text by using XPath on Selenium?

<td>
    <span class="td-title">city</span>
    <span>city</span>
    " Japan"
</td>

How to locate element on text by using XPath?如何使用 XPath 在文本上定位元素? I tried to use /td/text() but it showed "td/text()" is: [object Text]. It should be an element.我尝试使用/td/text()但它显示"td/text()" is: [object Text]. It should be an element. "td/text()" is: [object Text]. It should be an element. If I use /td it will return city city Japan , but I want the only output is Japan .如果我使用/td它将返回city city Japan ,但我想要唯一的 output 是Japan

I cannot use contain() or /td[text() = 'Japan'] to specific city "Japan", because I also want to find multiple different cities.我不能对特定城市“日本”使用contain()/td[text() = 'Japan'] ,因为我还想找到多个不同的城市。 If I use this functions, I'll have to manually change city's name every time.如果我使用这个功能,我每次都必须手动更改城市名称。

If you want to select td elements that have a text() node child that is not just whitespace, you can use如果你想要 select td元素有一个text()节点孩子,而不仅仅是空白,你可以使用

/td[text()[normalize-space()]]

But if you are selecting that element and ask for its computed string value, it will concat all of the text() node descendants.但是,如果您选择该元素并询问其计算字符串值,它将连接所有text()节点后代。

You would want to select only the immediate child text() value.您只需要 select 的直接子text()值。 It sounds like that is a common problem in Selenium: https://stackoverflow.com/a/28948550/14419听起来这是 Selenium 中的常见问题: https://stackoverflow.com/a/28948550/14419

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

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