无法定位元素 - 使用 selenium webdriver 在不同的语言环境中自动化网站

Unable to locate element - Automating a website in different locales using selenium webdriver

我正在尝试使具有不同度量系统的网站自动化。 该应用程序同时支持美国公制和英国公制。 例如:如果我从美国服务器打开应用程序,我会看到英尺和英寸的文本框,如果我从不同的服务器打开相同的应用程序,我会看到厘米的文本框。

我编写了我的代码,以便它首先检查是否存在带有英尺和英寸的文本框元素,如果存在则继续并在这些文本框中输入值,否则如果不存在英尺和英寸present,然后在“厘米”文本框中输入值。

/*
 *
 * This block is for the values in US version
 *
 */
@FindBy(xpath = ".//*[@id='profile_height_large_value']")
WebElement CurrentHeightinFeet;

@FindBy(xpath = ".//*[@id='profile_height_small_value']")
WebElement CurrentHeightinInches;

/*
 * This block is for the values in British version
 *
 */

@FindBy(xpath = ".//*[@id='profile_height_display_value']")
WebElement CurrentHeightinCM;

我检查它是否在任一版本中的代码如下。

public void userFitnessDetails() {
    CurrentWeight.sendKeys("70");

    if (CurrentHeightinFeet.isDisplayed()) {
        CurrentHeightinFeet.clear();
        CurrentHeightinFeet.sendKeys("5");
        CurrentHeightinInches.clear();
        CurrentHeightinInches.sendKeys("10");
    }

    CurrentHeightinCM.clear();
    CurrentHeightinCM.sendKeys("170");
}

如果我执行上面的代码,我会得到一个错误 - 失败:注册 org.openqa.selenium.NoSuchElementException:无法定位元素:

{"method":"xpath","selector":".//*[@id='profile_height_large_value']"}

有人可以指导我更正这个问题吗?

谢谢

假设 - 您正在英国服务器上工作,运行正在处理美国英尺长度输入的问题。页面已完全加载且元素完全可用,因此不存在等待问题。

您将 运行 遇到 isDisplayed() 方法的问题。它用于确定页面中存在的元素是否由于样式属性显示设置不可见,反之亦然。在这里,您提到了相关的 html 元素是否存在取决于服务器位置。如果该元素不可用,那么您将看到异常。

您可以使用更安全的 driver.findElements() 代替 isDiplayed() 条件检查,其中 returns 一个列表,您可以检查大小以确定可用性。