代码之家  ›  专栏  ›  技术社区  ›  Pitto

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

  •  2
  • Pitto  · 技术社区  · 7 年前

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

    因此,很明显,元素是动态地从DOM中注入和移除的。

    我知道我可以使用与WebDriverWait(我编写的非常简洁的模板)类似的代码等待元素出现在DOM中 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获得此类结果的更有效方法。

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

    谢谢你的时间和帮助。

    2 回复  |  直到 7 年前
        1
  •  2
  •   undetected Selenium    7 年前

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

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

      WebDriverWait wait = new WebDriverWait(driver, 10);
      
    • 当你调用 click() 方法因此而不是 预期条件 visibilityOfElementLocated() 方法使用 elementToBeClickable() 方法如下:

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

      By.xpath("//a[@class='i-am-your-class']")
      
    • 优化代码以调用 点击() 只要元素通过 WebDriverWait 详情如下:

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

    我不知道你为什么说 XPATH 优先考虑。我想补充一些关于定位器的内容。

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

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

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

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

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

    1. 身份证件
    2. 名称
    3. 类名
    4. 链接文本
    5. partialLinkText
    6. 标记名
    7. CSS选择器
    8. XPath .

    笔记 :大多数情况下,cssSelector可以取代Xpath,但是Xpath有cssSelector没有的优点。

    有关更多参考信息,请访问此SO链接: Xpath vs Css selector