简体   繁体   中英

How to find parent of two elements that match CssSelectors?

Given the following (generic) dynamic HTML structure:

<ol id="myOrderedList">
    <li id="someGuidICantPredict">
        <span data-serial="someData1">someData1</span>
        <span data-manufacturer="someDataB1">someDataB1</span>
    </li>
    //(repeated many times with different data)
</ol>

How do I find the following:

Find the <li> where the spans match by CssSelector for both data-serial and data-manufacturer ?

I know how to do this for one or the other span tag thusly:

By.CssSelector($"#olCurrentTanks li span[data-serial={serial1}]")

or

By.CssSelector($"#olCurrentTanks li span[data-manufacturer={manufacturer1}]")

But I don't know how to find the parent <li> element where both spans match. Meaning I need to get the IWebElement listItem where the both span's data attributes match the corresponding data which I can predict.

Edit: Difficulty: Okay to use x-path to get the li parent but not to find the spans.

With you can get li element with specific span s children:

//li[./span[@data-serial="someData1"] and ./span[@data-manufacturer="someDataB1"]]

Selector below will give all li elements as a list for FindElements and single first one for FindElement :

By.XPath("//li[./span[@data-serial='someData1'] and ./span[@data-manufacturer='someDataB1']]")

Code examples:

IList<IWebElement> allMyLi = driver.FindElements(By.XPath($"//li[./span[@data-serial='{serial1}'] and ./span[@data-manufacturer='{manufacturer1}']]"));

foreach (var myLi in allMyLi)
{
    IWebElement serial = myLi.FindElement(By.CssSelector($"span[data-serial={serial1}]"));
    IWebElement manufacturer = myLi.FindElement(By.CssSelector($"span[data-manufacturer={manufacturer1}]"));

    Console.WriteLine("serial, manufacturer: {0}, {1}", serial.Text, manufacturer.Text);
}

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