当前位置 博文首页 > python Selenium等待元素出现的具体方法

    python Selenium等待元素出现的具体方法

    作者:小妮浅浅 时间:2021-09-18 17:48

    有一个 Selenium 脚本(Python),它点击回复按钮使anonemail类出现。anonemail 类出现的时间各不相同。因此,我必须使用 sleep 直到元素出现。

    我想等到课程出现而不是使用睡眠。我听说过等待命令,但我不知道如何使用它们。

    这是我迄今为止所拥有的:

    browser.find_element_by_css_selector(".reply-button").click()
    sleep(5)
    email=browser.find_element_by_css_selector(".anonemail").get_attribute("value")

    解决:

    1、如果验证任何元素的存在,检查元素期望

    诱导WebDriverWait设置expected_conditions作为presence_of_element_located()检查元素是否存在于页面的 DOM 上的期望。这并不一定意味着该元素是可见的。所以有效的代码行将是:

    WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".reply-button"))).click()

    2、如果提取任何元素的任何属性,检查元素可见的期望

    需要诱导WebDriverWait设置。expected_conditions作为visibility_of_element_located(locator)检查元素是否存在于页面的 DOM 上并且可见的期望。可见性意味着元素不仅被显示,而且高度和宽度都大于 0。所以在你的用例中,代码行将是:

    email = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "element_css"))).get_attribute("value")

    3、如果用例要click()在任何元素上调用,检查元素是否可见并启用

    要诱导WebDriverWait设置expected_conditions作为element_to_be_clickable()检查元素是否可见并启用以便您可以单击它的期望。所以在你的用例中,代码行将是:

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".reply-button"))).click()

    实例扩展:

    from selenium.common.exceptions import TimeoutException
    from selenium.webdriver.common.by import By
    import selenium.webdriver.support.expected_conditions as EC
    import selenium.webdriver.support.ui as ui
    
    
    
    # 一直等待某元素可见,默认超时10秒
    def is_visible(locator, timeout=10):
        try:
            ui.WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.XPATH, locator)))
            return True
        except TimeoutException:
            return False
    
    # 一直等待某个元素消失,默认超时10秒
    def is_not_visible(locator, timeout=10):
        try:
            ui.WebDriverWait(driver, timeout).until_not(EC.visibility_of_element_located((By.XPATH, locator)))
            return True
        except TimeoutException:
            return False
    jsjbwy
    下一篇:没有了