Selenium webdriver 有时找不到元素

Selenium webdriver can't find element sometimes

我试图在 tripadvisor 上找到搜索框,但有时找不到。 (我收到超时错误)。我添加了 WebDriverWait 和 time.sleep 但无济于事。我仍在测试中,所以我的部分代码需要下面的人工干预。

编辑:更改为 time.sleep(10) 而不是 5 秒会有所帮助。但它使代码非常慢。希望改用 WebDriverWait...

searchbox = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='Where to?']")))

下面是我的完整代码,我必须在其中多次找到每个国家/地区的搜索框。

from selenium.webdriver.common.by import By
from selenium import webdriver 
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome(executable_path=r'C:\Users\user\Downloads\chromedriver.exe') 
driver.get("https://www.tripadvisor.com.sg/Hotels-g293951-Malaysia-Hotels.html")

此处人为干预:点击随机入住日期、退房日期,然后点击“更新”

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+countries5

for 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)

search input框中输入值

使用 WebDriverWait() 并等待 element_to_be_clickable() 并遵循 xpath。

searchbox = WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH, "//input[@aria-label='Search']")))

要在 Tripadvisor instead of presence_of_element_located() you have to induce for the element_to_be_clickable() and you can use either of the following 上找到搜索框:

  • 使用CSS_SELECTOR:

    searchbox = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='q'][title='Search']")))
    
  • 使用XPATH:

    searchbox = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='q' and @title='Search']")))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC