首页 > 解决方案 > Selenium:等待元素加载

问题描述

我还是 Selenium 的新手,很抱歉提出愚蠢的问题。我一直在尝试找到一种方法让 selenium 等到加载元素。该元素在弹出窗口中<div>,我需要滚动到底部以无限加载 pop-up <div>。在 Selenium 的文档中,他们说要这样使用WebdriverWait

while i <= 1000:
    try:
        #The xpath for the element I am trying to scroll to
        xpath = '/html/body/div[16]/div/div[1]/div/div[2]/div/div[1]/ul/li[' + str(i) +']'

        #Selenium's way of waiting for the presence of an element
        element = WebDriverWait(driver, 10).until(EC.presence_of_element_located(By.XPATH, xpath))

        #Scrolling to that element
        driver.execute_script("arguments[0].scrollIntoView(true);", element)
        i += 10

    except:
        print('Failed', i)

    time.sleep(2)

WebdriverWait似乎没有工作。如果我只是向下滚动并使用time.sleep(2)等待元素加载。有用。但是,我尝试加载的页面并没有延迟加载已经加载的内容。因此,html 将所有加载的元素存储在弹出窗口中<div>,一旦 div 更新,最好向下滚动。div 越大,下一次加载所需的时间就越长。我想如果存在的话,我正在寻找对 Selenium 的动态等待。

标签: pythonhtmlselenium

解决方案


您可以参考 selenium 中的隐式等待。隐式等待将指示 Web 驱动程序在抛出“无此类元素异常”之前等待一定时间。(隐式等待时间应用于会话脚本中的所有元素)

你可以像下面这样实现它: -

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;

这意味着如果该元素在该时间范围(10 秒)内未位于网页上,则会引发异常。

  1. Selenium 中的其他等待是显式等待。显式等待用于告诉 Web Driver 在抛出“ElementNotVisibleException”异常之前等待某些条件(预期条件)或超过的最长时间。

你可以像下面这样实现它

WebDriverWait wait=new WebDriverWait(driver, 20);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'STACKOVERFLOW')]")));

与您的情况一样,它与警报有关,请尝试使用`

 wait.until(ExpectedConditions.alertIsPresent());
  1. 在硒中帮助您的最后一个等待是 Fluent Waits

它定义了 WebDriver 在抛出“ElementNotVisibleException”之前检查条件是否出现的频率。

简单地说,Fluent Wait 会定期(由您定义)重复查找 Web 元素,直到发生超时或直到找到对象。

当您尝试测试可能在 x 秒/分钟后出现的元素的存在时,您应该使用它。

要实现流畅的等待,请尝试以下示例代码:-

 Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(20, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);

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

推荐阅读