Selenium - 等待元素出现、可见和可交互 [英] Selenium - wait until element is present, visible and interactable

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

问题描述

我有一个 Selenium 脚本 (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.

这是我目前所拥有的:

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()

  • 如果您的用例是提取任何元素的任何属性,您需要引入 WebDriverWait 设置 expected_conditions 作为 visibility_of_element_located(locator) 这是检查元素是否存在于页面的 DOM 上并且可见的期望.可见性意味着元素不仅被显示,而且高度和宽度都大于 0.所以在你的用例中,代码行将是:

  • 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")
    

  • 如果您的用例是在您需要诱导 WebDriverWait 设置 expected_conditions作为 element_to_be_clickable() 这是检查元素是否可见并启用以便您可以单击它的期望.因此,在您的用例中,代码行将是:

  • 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:

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

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