简体   繁体   中英

Find nth element by tag name within element found by ID using XPath or CssSelector

I need to grab the third span element, inside an A element, that is also inside an LI element that has an ID. I want to use the ID to first find the LI element, then within that, find the 3rd span element. HTML example:

<li id='MyID'>
<a href="MyHRef">
<span>first span</span>
<span>second span</span>
<span>third span</span>
</a>
</li>

I tried the following, but I dont think I have it written correctly:

public readonly By Menu_ProgramMatchingNumber = By.XPath("li[@id='MyID']/following-sibling::span[3]");

According to XPath syntax:

http://www.w3schools.com/xml/xpath_syntax.asp

You may want to use: //li[@id='MyID']/a/span[3]

Or more specific: //li[@id='MyID']/a[@href='MyHRef']/span[3]

使用CSS:

By.CssSelector("li#MyID a > span:nth-of-type(3)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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