gpt4 book ai didi

python - selenium 中的隐式或显式等待不能通过 time.sleep 可靠地工作?

转载 作者:行者123 更新时间:2023-12-01 07:03:07 25 4
gpt4 key购买 nike

我有一些selenium代码可以登录jupyterlab(在本地运行)。如果不等待,它会失败,因为它试图在密码输入文本框存在之前找到它。因此,我尝试使用显式等待,因为这似乎是最干净的解决方案,但它的工作不稳定。隐式等待永远不会起作用,它似乎会在加载页面之前阻塞网络服务器 10 秒,因此总是失败。 time.sleep 总是有效,但是它加载页面,然后在输入密码之前等待 10 秒,这比 selenium 等待方法效率低下且不太干净,据我所知,selenium 等待方法最多等待 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: Message: Element is not reachable by keyboard

  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: Message: Element is not reachable by keyboard

  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)

    虽然这总是有效,但它无缘无故地浪费时间。 Selenium 等待方法确实应该有效。

我做错了什么?

最佳答案

同时How to resolve ElementNotInteractableException: Element is not visible in Selenium webdriver?从技术上讲,它是一个重复项,它为 Java 解决了这个问题,当重复项用于不同的语言时,它总是让我烦恼,所以我将为 Python 编写这个答案。

<小时/>

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

等待元素“可点击”通常是最好的解决方案:

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)

关于python - selenium 中的隐式或显式等待不能通过 time.sleep 可靠地工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58555769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com