Python+;Selenium:在WebDriverWait调用超时后重新加载页面
我正在寻找一种在Python Selenium中实现以下内容的正确方法Python+;Selenium:在WebDriverWait调用超时后重新加载页面,python,selenium,loops,selenium-webdriver,webdriverwait,Python,Selenium,Loops,Selenium Webdriver,Webdriverwait,我正在寻找一种在Python Selenium中实现以下内容的正确方法 载入一页 等待一段时间(例如30秒)按钮才可单击(通过调用WebDriverWait) 如果获得TimeoutException,请再次重新加载页面,即转到步骤1) url='1〕https://...' driver=webdriver.Chrome(“./chromedriver”) 尝试: 获取驱动程序(url) wait=WebDriverWait(驱动程序,30) element=wait.until(EC.ele
url='1〕https://...'
driver=webdriver.Chrome(“./chromedriver”)
尝试:
获取驱动程序(url)
wait=WebDriverWait(驱动程序,30)
element=wait.until(EC.element可点击((By.CLASS\u NAME,'button'))
除TimeoutException作为e外:
您可以创建一个函数,如果找不到元素,该函数将自动调用刷新
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import os
driver = webdriver.Chrome(executable_path =os.path.abspath(os.getcwd()) + "/chromedriver")
driver.get("https://selenium-python.readthedocs.io/waits.html")
def refresh():
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "button"))
)
except:
driver.refresh()
refresh()
refresh()
您可以使用
按钮作为类名在Dom中显示元素时,使用显式等待
获取元素列表。若元素列表为空,则可以刷新页面
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
url = 'https://...'
driver = webdriver.Chrome('./chromedriver')
driver.get(url)
wait = WebDriverWait(driver, 30)
if len(wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME,'button'))))==0 :
driver.refresh()
要执行以下任务:
载入一页
等待一段时间(例如30秒)按钮才可单击(通过调用WebDriverWait)
如果获得TimeoutException,请再次重新加载页面,即转到步骤1)
您可以使用以下命令。为了演示,我将考虑一个不可用的元素:
- 代码块:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
while True:
try:
driver.get("https://www.google.com/")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, "kokei")))
print("Button found")
break
except TimeoutException:
print("Button not found ... reloading page")
continue
# perform your remaining steps here on successfully finding the clickable element
driver.quit()
- 控制台输出:
Button not found ... reloading page
Button not found ... reloading page
Button not found ... reloading page
Button not found ... reloading page
Button not found ... reloading page
Button not found ... reloading page