我正在寻找在下面的Python Selenium中实现的正确方法
url = 'https://...'
driver = webdriver.Chrome('./chromedriver')
try:
driver.get(url)
wait = WebDriverWait(driver, 30)
element = wait.until(EC.element_to_be_clickable((By.CLASS_NAME,'button')))
except TimeoutException as e:
<reload the url again>
您可以创建一个函数,如果未找到该元素,将自动通过刷新调用。
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中以explicit wait
为button
的形式获取具有class name
的元素的列表。如果元素列表为空,则可以刷新页面。
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()
要执行以下任务:
您可以使用以下Locator Strategy。为了演示,我将考虑一个在Google Search Home Page中不可用的元素:
代码块:
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