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

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

因此,很明显,元素会动态地从DOM中注入和删除。

我知道我可以使用类似的代码使用WebDriverWait等待一个元素出现在DOM中(非常简洁的模板我写了稍微改变的GitHub ):

public void waitForElement() throws Exception { /* Inject the following snippet in any web page to test the method  */ 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,几个答案指向类似的方向,但没有答案专注于效率/性能:

  • WebDriver – 使用Java等待元素
  • Selenium WebDriver:当使用WebDriver.findElement定位时,等待元素存在是不可能的

感谢您的时间和帮助。

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

  • 100的 WebDriverWait()不应该是实时服务员。 考虑按照测试规范减少它。 例如,将其设置为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,包括在By.xpath("//tagName[@class='i-am-your-class']")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. class级名称
  4. LINKTEXT
  5. partialLinkText
  6. 标签名称
  7. cssSelector
  8. XPath

注意 :大多数时候cssSelector可以替换Xpath,但是Xpath有自己的优点,cssSelector没有提供。

有关更多参考,您可以浏览此SO链接: Xpath与Css选择器