在python中,是否可以创建一个无限循环来搜索页面中的元素



我正在尝试创建一个循环,用于搜索页面中的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()

但是不可能定义cart,因为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

最新更新