简体   繁体   中英

Selenium (Java) how to find an element from a list of possible elements

selenium 的新手,为了简化它,有 50 个可能的元素可以出现在页面上,所以我有这 50 个 driver.findElement(By.xpath().click(),点击任何可能出现的元素,我的问题是,如果 findelement 是 flase 程序结束,但我想要的是检查第一个元素,如果它是假的,检查第二个,如果第二个是假的,检查第三个,直到它找到 findelement true 并点击它。最好的方法是什么?谢谢。

How different are the elements? That will help produce a better answer but the answer to the second part of the question... how do you check for an element and then proceed if not found, I would do something like this.

Build a List<> of your locators (the By.* stuff), loop through them looking for one that matches, if you find a match then click it.

List<By> locators = new ArrayList<>();
locators.add(By.id("someId"));
locators.add(By.cssSelector("div.someClass"));
// add all your locators to the List<>

for (By locator : locators)
{
    List<WebElement> elements = driver.findElements(locator);
    if (elements.size() > 0)
    {
        elements.get(0).click();
        break;
    }
}

创建一个 xpath 数组,然后循环遍历它们,直到命中某个元素。

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