硒-等待元素存在,可见且可交互 [英] Selenium - wait until element is present, visible and interactable

查看:110
本文介绍了硒-等待元素存在,可见且可交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个硒脚本(python),单击一个答复按钮以使该类anonemail出现.出现班级anonemail所需的时间有所不同.因此,我必须使用sleep直到元素出现.我想等到班级出现,而不要使用睡眠.我听说过等待命令,但是我不知道如何使用它们.

I have a selenium script (python) that clicks a reply button to make the class anonemail appear. The time it takes for the class anonemail to appear varies. Because of that I have to use sleep until the element has appeared. I want to wait until the class has appeared instead of using sleep. I have heard about wait commands, but I don't know how to use them.

这是我到目前为止所拥有的:

This is what I have thus far:

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

推荐答案

根据最佳做法:

  • 如果您的用例是验证任何元素的存在,则需要诱导

  • If your usecase is to validate the presence of any element you need to induce WebDriverWait setting the expected_conditions as presence_of_element_located() which is the expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible. So the effective line of code will be:

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

  • 如果用例是要提取任何元素的任何属性,则需要引入

  • If your usecase is to extract any attribute of any element you need to induce WebDriverWait setting the expected_conditions as visibility_of_element_located(locator) which is an expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. So in your usecase effectively the line of code will be:

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

  • 如果您的用例是对任何元素调用 click() ,则需要诱导

  • If your usecase is to invoke click() on any element you need to induce WebDriverWait setting the expected_conditions as element_to_be_clickable() which is an expectation for for checking an element is visible and enabled such that you can click it. So in your usecase effectively the line of code will be:

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

  • 您可以在以下位置找到一些详细的讨论:

    You can find a couple of detailed discussion in:

    • WebDriverWait not working as expected
    • Selenium: Check for the presence of element

    这篇关于硒-等待元素存在,可见且可交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆