Selenium webdriver 有時(shí)找不到元素
我試圖在 tripadvisor 上找到搜索框,但有時(shí)找不到。(我收到超時(shí)錯(cuò)誤)。我添加了 WebDriverWait 和 time.sleep 但沒(méi)有效果。我仍在測(cè)試中,因此下面我的代碼中有一部分需要人工干預(yù)。編輯:更改為 time.sleep(10) 而不是 5 秒會(huì)有所幫助。但這使得代碼非常慢。希望改用 WebDriverWait...searchbox = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='Where to?']")))下面是我的完整代碼,我必須為每個(gè)國(guó)家多次找到搜索框。from selenium.webdriver.common.by import Byfrom selenium import webdriver from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECimport timedriver = webdriver.Chrome(executable_path=r'C:\\Users\\user\\Downloads\\chromedriver.exe') driver.get("https://www.tripadvisor.com.sg/Hotels-g293951-Malaysia-Hotels.html")此處人工干預(yù):點(diǎn)擊隨機(jī)入住日期、退房日期,然后點(diǎn)擊“更新”countries3 = ["France","Qatar","Brunei Darussalam","Hong Kong"]countries4 = ["Germany","The Netherlands","Nigeria","South Africa","Russia"]countries2 = ["New York","Saudi Arabia","Sri Lanka","Switzerland","Turkey"]countries1 = ["United Arab Emirates","New Zealand","Thailand","India"]countries5 = ["Vietnam","Australia","Malaysia","Cambodia","Indonesia","Laos","Myanmar","Philippines","Thailand","Vietnam","Australia", "Canada","China","Japan","Taiwan","United Kingdom","United States","Bangladesh","Belgium","Egypt","Finland"]countries = countries1+countries2+countries3+countries4+countries5for country in countries: driver.get(URL) driver.implicitly_wait(10) time.sleep(5) searchbox = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='Where to?']"))) searchbox.send_keys(country) #select your destination here time.sleep(2) possible = driver.find_elements_by_class_name("_3a_rGDNB") for i in possible: if i.text == country: i.click() break time.sleep(5) hotels = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//*[@title="Hotels"]'))) driver.execute_script("arguments[0].click();", hotels) time.sleep(3)
查看完整描述