等待页面元素 (xpath) 出现在 Selenium Webdriver 中的最有效方法是什么?

What is the most efficient way to wait for a page element (xpath) to show up in Selenium Webdriver?

我正在使用 Java 和 Selenium Webdriver 来测试单页 Web 应用程序的功能。

出于这个原因,显然,元素是动态注入和从 DOM 中删除的。

我知道我可以使用类似的代码等待元素出现在 DOM 中,该代码使用 WebDriverWait(我写的非常简洁的模板,略有改动 GitHub):

public void waitForElement() throws Exception {
    /*
    Inject the following snippet in any web page to test the method
    <button class="i-am-your-class" onclick="alert('Wow, you pressed the button!');">Press me</button>
     */
    System.setProperty("webdriver.gecko.driver", "C:\Program Files (x86)\Mozilla Firefox\geckodriver.exe");
    WebDriver driver = getDriver();
    WebDriverWait wait = new WebDriverWait(driver, 10); // 10 can be reduced as per Test Specifications
    driver.get("http://www.google.com");
    WebElement response = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@class='i-am-your-class']")));
    response.click();
    System.out.println("*****************************************************************************");
    System.out.println(response);
    System.out.println(response.getText());

    driver.close();
}

我想知道这是否也是使用 xpath 获得此类结果的更有效方法。

我一直在研究 Whosebug,有几个答案指向相似的方向,但没有答案关注效率/性能:

感谢您的宝贵时间和帮助。

您需要考虑以下几个事实:

  • WebDriverWait() for 100 不应该是实时服务员。考虑根据 测试规范 减少它。例如,将其设置为 10 秒:

    WebDriverWait wait = new WebDriverWait(driver, 10);
    
  • 在调用 click() 方法时向前移动,因此不要将 ExpectedConditions 作为 visibilityOfElementLocated() 方法使用 elementToBeClickable() 方法如下:

    WebElement response = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@class='i-am-your-class']")));
    
  • 优化您的 xpath,包括 tagName,如 By.xpath("//tagName[@class='i-am-your-class']")。例如:

    By.xpath("//a[@class='i-am-your-class']")
    
  • 优化您的代码以在通过 WebDriverWait 返回元素后立即调用 click(),如下所示:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='i-am-your-class']"))).click();
    

我不知道你为什么说 XPATH 是首选。我想补充一些关于定位器的内容。

您在代码中编写的 XPATH 可以很容易地替换为 css selector。这是例子。

div[class='i-am-your-class']  

现在的主要问题是为什么要切换到不同的定位器?

  • 效率更高。
  • 与 xpath 相比速度更快。
  • 更靠谱。
  • 更多性能。

您应该始终按照 Selenium 贡献者 建议的顺序使用定位器

  1. ID
  2. 姓名
  3. 类名
  4. linkText
  5. 部分Link正文
  6. 标签名
  7. cssSelector
  8. XPath

注意 : 大多数情况下,cssSelector 可以替代 Xpath,但是 Xpath 有其自身的优点,而 cssSelector 没有。

如需更多参考,您可以查看此 SO Link:Xpath vs Css selector