How Selenium's ByChained class really works?

后端 未结 3 977
一生所求
一生所求 2020-12-30 08:10

I am very confused with what the documentation for ByChained class mentions. It says:

Mechanism used to locate elements within a docu

相关标签:
3条回答
  • 2020-12-30 08:27

    Your request would be satisfied by something that could be called ByAny which would return elements that match any of the passed By arguments. There's no such class AFAIK.

    However, ByChained works differently. It finds the elements that are matched by the first argument, then searches their descendants using the second argument etc. So, if you had HTMl like this:

    <html>
        <body>
            <div id="details">
                <input id="firstName" class="personName" type="text"/>
            </div>
            <div id="notDetails">
                <input id="secondName" class="personName" type="text"/>
            </div>
        </body>
    </html>
    

    and you wanted to find the class=personName element under id=details, you could either use a CSS selector, an XPath expression, or the

    new ByChained(By.id("details"), By.className("personName"))
    

    Note that there also is a ByAll class that searches for elements matched by all of the By arguments passed.

    0 讨论(0)
  • 2020-12-30 08:35

    What this class does is allow you to locate an element using its heirarchy in the dom.

    lets say for some reason you have the following html:

    <html>
        <body>
            <div id="details">
                <input id="firstName" class="personName" type="text"/>
            </div>
            <input id="firstName" class="personName" type="text"/>
        </body>
    </html>
    

    and you want to get the element that is between the div rather than the one on its own. You can use the ByChained by to specify that you want that element by doing the following:

    new ByChained(By.id("details"),By.id("firstName"));
    

    What happens is that it finds the first element then searches underneath that in the dom heirarchy for the selector that comes next in the list. Basically this By is just a nice clean way of no longer having to do the following:

    details = driver.findElement(By.id("details"));
    input = details.findElement(By.id("firstName"));
    
    0 讨论(0)
  • 2020-12-30 08:39

    It's probably important to note (because I never see anyone mention this) that ByChained should be used just like any other By locator, like so:

    driver.findElements( new ByChained(By.id("details"), By.className("personName")) )
    

    or

    driver.findElements( new ByAll(By.id("err1"), By.className("errBox")) )
    
    0 讨论(0)
提交回复
热议问题