python - 我如何使用 Selenium 的等待?

标签 python selenium

我在弄清楚如何使用 Selenium 的等待函数时遇到了麻烦。我想做的是检查一个元素是否存在,如果存在,它将打印一条语句。这是我的代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
browser.get("http://google.com")
delay = 3 # seconds
try:
    WebDriverWait(browser, delay).until(EC.presence_of_element_located(browser.find_element_by_xpath('//*[@id="hplogo"]')))
    print ("Page is ready!")
except TimeoutException:
    print ("Loading took too much time!")

当前代码给我以下错误:

Traceback (most recent call last):
  File "/Users/John/Documents/waitTest.py", line 10, in <module>
    WebDriverWait(browser, delay).until(EC.presence_of_element_located(browser.find_element_by_xpath('//*[@id="hplogo"]')))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/support/wait.py", line 71, in until
    value = method(self._driver)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/support/expected_conditions.py", line 59, in __call__
    return _find_element(driver, self.locator)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/support/expected_conditions.py", line 274, in _find_element
    return driver.find_element(*by)
TypeError: find_element() argument after * must be a sequence, not WebElement

最佳答案

预期条件 expects要传入的元组,其中第一项是定位器的类型(By 常量),第二项是定位器的值:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC    

wait = WebDriverWait(browser, 10)
wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="hplogo"]')))

请注意,在您的情况下 By.ID 会更简单:

wait.until(EC.presence_of_element_located((By.ID, 'hplogo')))

关于python - 我如何使用 Selenium 的等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34504839/

相关文章:

python - 从python执行awk命令

python - Django 登录无法正常工作

Python:有没有办法从包装它的装饰器中获取局部函数变量?

java - Selenium Chrome 驱动程序针对属性标签

c# - 如何在不关闭同一浏览器实例的情况下运行多个测试方法(C#、SeleniumWebDriverz NUnit)?

java - Selenium - 以编程方式将 html 转换为 junit

python - 在 Python 中合并不同的字典

javascript - 使用 selenium 在 iframe 中注入(inject) Javascript

java - 构造“try/catch”不会捕获异常“NoSuchElementException”

javascript - 向 Flask render_template 端点发出客户端 POST 请求