在 selenium 中定位 WebElements 的子节点 [英] Locating child nodes of WebElements in selenium
问题描述
我正在使用 selenium 来测试我的 Web 应用程序,我可以使用 By.xpath
成功找到标签.但是,有时我需要在该节点中找到子节点.
示例:
<div><跨度/><输入/>
我能做到:
WebElement divA = driver.findElement( By.xpath( "//div[@id='a']" ) )
但现在我需要找到输入,所以我可以这样做:
driver.findElement( By.xpath( "//div[@id='a']//input" ) )
然而,在代码中我只有 divA
,不再是它的 xpath...我想做这样的事情:
WebElement input = driver.findElement( divA, By.xpath( "//input" ) );
但是这样的功能并不存在.我可以这样做吗?
顺便说一句:有时我需要找到一个 <div>
,它有一个特定的后代节点.如何在 xpath 中询问包含 和文本
'hello world'
的
根据 JavaDocs,你可以这样做:
WebElement input = divA.findElement(By.xpath(".//input"));
<小时><块引用>
如何在 xpath 中询问包含跨度的 div 标签文本'你好世界'"?
WebElement elem = driver.findElement(By.xpath("//div[span[text()='hello world']]"));
XPath 规范是一本令人惊讶的好书.
I am using selenium to test my web application and I can successfully find tags using By.xpath
. However now and then I need to find child nodes within that node.
Example:
<div id="a">
<div>
<span />
<input />
</div>
</div>
I can do:
WebElement divA = driver.findElement( By.xpath( "//div[@id='a']" ) )
But now I need to find the input, so I could do:
driver.findElement( By.xpath( "//div[@id='a']//input" ) )
However, at that point in code I only have divA
, not its xpath anymore... I would like to do something like this:
WebElement input = driver.findElement( divA, By.xpath( "//input" ) );
But such a function does not exist. Can I do this anyhow?
BTW: Sometimes I need to find a <div>
that has a certain decendent node. How can I ask in xpath for "the <div>
that contains a <span>
with the text 'hello world'
"?
According to JavaDocs, you can do this:
WebElement input = divA.findElement(By.xpath(".//input"));
How can I ask in xpath for "the div-tag that contains a span with the text 'hello world'"?
WebElement elem = driver.findElement(By.xpath("//div[span[text()='hello world']]"));
The XPath spec is a suprisingly good read on this.
这篇关于在 selenium 中定位 WebElements 的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!