Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

java - Locating child nodes of WebElements in selenium

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'"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...