我在弄清楚如何使用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
答案 0 :(得分:13)
预期条件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')))
答案 1 :(得分:1)
您需要导入By
模块
from selenium.webdriver.common.by import By