在 python 中是否可以创建无限循环来搜索页面中的元素?
In python is possible to create an infinite loop for searching an element in a page?
我正在尝试创建一个循环来搜索页面中的 xpath 直到可用。
我正在尝试这样做:
cart = driver.find_element_by_xpath('//*[@id="add-to-cart-button"]')
if not cart:
webdriver.ActionChains(driver).send_keys(Keys.F5).perform()
else:
driver.find_element_by_xpath('//*[@id="add-to-cart-button"]').click()
但是无法定义购物车,因为 xpath 尚不可用。
你是怎么做到的?
将 click()
包裹在 try/catch{}
块中,如下所示:
while True:
try:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='add-to-cart-button']"))).click()
break
except TimeoutException:
driver.ActionChains(driver).send_keys(Keys.F5).perform()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
我正在尝试创建一个循环来搜索页面中的 xpath 直到可用。
我正在尝试这样做:
cart = driver.find_element_by_xpath('//*[@id="add-to-cart-button"]')
if not cart:
webdriver.ActionChains(driver).send_keys(Keys.F5).perform()
else:
driver.find_element_by_xpath('//*[@id="add-to-cart-button"]').click()
但是无法定义购物车,因为 xpath 尚不可用。
你是怎么做到的?
将 click()
包裹在 try/catch{}
块中,如下所示:
while True:
try:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='add-to-cart-button']"))).click()
break
except TimeoutException:
driver.ActionChains(driver).send_keys(Keys.F5).perform()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains