硒中的隐式或显式等待不能按时间可靠地工作。睡眠可以吗?

时间:2019-10-25 09:27:10

标签: python selenium wait

我有一些硒代码可以登录jupyterlab(在本地运行)。如果不等待,它将失败,因为它尝试在密码输入文本框存在之前找到它。因此,我尝试使用显式等待,因为这似乎是最干净的解决方案,但它工作不正常。隐式等待永远不会起作用,它似乎在加载页面之前将Web服务器阻塞了10秒钟,因此总是失败。 time.sleep始终有效,但是它会加载页面,然后等待10秒钟,然后再输入密码,效率比硒等待方法低,而且不干净,据我所知,硒等待方法最多等待10秒钟,但一旦元素变为可用。我做错了什么?

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait
  1. 明确等待-有时可行

    driver = webdriver.Firefox()
    driver.get(f"http://localhost:8888")
    wait = WebDriverWait(driver, 10)
    password_input = wait.until(ec.presence_of_element_located((By.ID, "password_input")))
    password = "my_password"
    password_input.send_keys(password + Keys.RETURN)
    

    有时我会收到错误消息:

      

    selenium.common.exceptions.ElementNotInteractableException:消息:键盘无法访问元素

  2. 隐式等待-有时会出错

    driver = webdriver.Firefox()
    driver.get(f"http://localhost:8888")
    driver.implicitly_wait(10)
    password_input = driver.find_element_by_css_selector("password_input")
    password = "my_password"
    password_input.send_keys(password + Keys.RETURN)
    

    有时我会收到错误消息:

      

    selenium.common.exceptions.ElementNotInteractableException:消息:键盘无法访问元素

  3. time.sleep-始终有效

    driver = webdriver.Firefox()
    driver.get(f"http://localhost:8888")
    time.sleep(10)
    password_input = driver.find_element_by_id("password_input")
    password = "my_password"
    password_input.send_keys(password + Keys.RETURN)
    

    尽管这始终有效,但无故浪费时间。硒等待方法确实应该起作用。

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

虽然How to resolve ElementNotInteractableException: Element is not visible in Selenium webdriver?从技术上讲是重复的,但它为Java解决了这个问题,当重复是针对另一种语言时,它总是让我很烦,所以我将为Python编写此答案。


ec.presence_of_element_located(...)方法仅测试文档对象模型中元素的存在。它不能确保用户可以与之交互的元素。另一个元素可能与它重叠,或者在调用password_input.send_keys(...)之前,该元素可能会在一段时间内隐藏起来。

等待直到元素“可点击”通常是最佳解决方案:

driver = webdriver.Firefox()
driver.get(f"http://localhost:8888")
wait = WebDriverWait(driver, 10)

# waiting until element is "clickable" means user can interact with
# it, and thus send_keys(...) can simulate keyboard interaction.
password_input = wait.until(ec.element_to_be_clickable((By.ID, "password_input")))

password = "my_password"
password_input.send_keys(password + Keys.RETURN)