如何解决Selenium Webdriver有时找不到元素
我正在尝试在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","Vietnam","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,"//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,'//*[@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而不是presence_of_element_located()
上找到搜索框,您必须为element_to_be_clickable()
引入WebDriverWait,并且可以使用以下任一Locator Strategies :
-
使用
CSS_SELECTOR
:searchbox = WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input[name='q'][title='Search']")))
-
使用
XPATH
:searchbox = WebDriverWait(driver,"//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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。