selenium将一直等待到x秒,如果超过x秒,则重新加载浏览器python
在上面的代码中,如果页面在60秒内没有正确加载,它只会跳到下一个关键字 在我正在处理的实际情况中,有超过10k的数据需要处理,我不应该错过任何一个 所以,我想在代码中加入一些if,else条件,即abt等待时间。 我有没有办法对等待时间设定条件 比如说,selenium将一直等待到x秒,如果超过x秒,则重新加载浏览器python,python,selenium,Python,Selenium,在上面的代码中,如果页面在60秒内没有正确加载,它只会跳到下一个关键字 在我正在处理的实际情况中,有超过10k的数据需要处理,我不应该错过任何一个 所以,我想在代码中加入一些if,else条件,即abt等待时间。 我有没有办法对等待时间设定条件 比如说, 最多等待60秒以查找元素 如果最后60秒过去了,则关闭driver.close()并重新加载驱动程序 您可以在中使用WebDriverWait,尝试/,但此处的块除外 from selenium import webdriver from se
您可以在
中使用WebDriverWait
,尝试/,但此处的块除外
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("http://www.someurl.com/")
wait = WebDriverWait(driver, 60)
def search_automation(keyword):
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".input_keyword").send_keys(keyword)
keyword_list = ['a','b','c']
for i in keyword_list:
search_automation(i)
只需将一个选择器,如(By.CSS\u selector,.input\u keyword”)
传递到方法中。该元素将等待60秒,如果该元素不存在,它将刷新页面。异常将是超时异常,而不是没有此类元素。WebDriverWait将等待60秒,然后超时,引发异常。它的TimeoutException,而不是WebDriverTimeoutException。。我刚刚更新了答案,还修复了导入,
from selenium.common.exceptions import TimeoutException
def wait_for_element(by):
try:
# wait up to 60 seconds for the element
WebDriverWait(driver, 60).until(EC.presence_of_element_located(by))
# if we hit exception, element was not found, and we should reload
except TimeoutException():
driver.refresh()