在 webdriver 中查找任意两个元素

2024-01-23

在我的应用程序中,当我打开页面 X 时,我希望看到元素 A 或元素 B。它们被放置在 DOM 中的不同位置,并且可以使用它们的 id 找到,例如driver.findElement(By.id("idA"))

我怎样才能让 webdriver 找到 A 或 B?

有方法driver.findElements(By)当至少找到一个元素时,它将停止等待,但这种方法迫使我对 A 和 B 使用相同的定位器。

可靠地找到 A 或 B 的正确方法是什么,这样我就不必等待隐式超时?


id 为 I1 的元素或 id 为 I2 的元素

xpath: //E1[@id=I1] | //E2[@id=I2]

css: css=E1#I1,E2#I2

driver.findElement(By.xpath(//E1[@id=I1] | //E2[@id=I2]))
driver.findElement(By.cssSelector(E1#I1,E2#I2))

不要忘记 fluidWait 机制:

public WebElement fluentWait(final By locator){

        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(30, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring(org.openqa.selenium.NoSuchElementException.class);

        WebElement foo = wait.until(
                new Function<WebDriver, WebElement>() {
                    public WebElement apply(WebDriver driver) {
                        return driver.findElement(locator);
                    }
                }
        );
        return  foo;
};

您可以获得有关 fluenceWait 的更多信息here http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html

恕我直言,您的问题的解决方案如下:

fluentWait(By.xpath(//E1[@id=I1] | //E2[@id=I2]));
fluentWait(By.cssSelector(E1#I1,E2#I2))

FYI: here http://www.simple-talk.com/dotnet/.net-framework/xpath,-css,-dom-and-selenium-the-rosetta-stone/很好xpath,cssSelector手册

希望这对你有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 webdriver 中查找任意两个元素 的相关文章

随机推荐