首页 > 解决方案 > 使用 Selenium 定位 webdriver 元素失败 |

问题描述

使用 selenium 自动化 webdriver 我无法使用 python 在旅游网站上找到文本框元素。使用 webdriver 中存在的定位器,例如 Id/name/css_selector/class_name 或 xpath/full xpath。下面是python代码的截图:[Code_1][1]

虽然第一个位于第二个不是。对应的 HTML 代码为 [text_box2][2]

我如何填写(自动化)两个文件对应的航班目的地,即离开和去 [1]:https ://i.stack.imgur.com/gpoIr.jpg [2]:https ://i.stack.imgur.com /Q7mgs.jpg

标签: pythonselenium

解决方案


这是一种稍微不同的定位方法。我在这个线程中使用从 CruisePandey 借来的等待。我用的是Firefox,但那是适应性强的。一些困难的注释:

我必须确保在航班选项卡上。我必须单击 from 和 to 字段,毕竟它们是按钮,然后等待能够输入显示的输入字段。最后,我必须从产生的下拉列表中选择第一个元素。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox(executable_path='/usr/bin/geckodriver')
driver.maximize_window()
driver.get('https://www.expedia.co.in')
wait = WebDriverWait(driver, 15)
wait.until(EC.presence_of_element_located((By.LINK_TEXT, "Flights")))
driver.find_element_by_link_text('Flights').click()
wait.until(EC.presence_of_element_located((By.ID, "location-field-leg1-origin")))
driver.find_element(By.CLASS_NAME,'uitk-faux-input').click()
fieldInput = driver.find_element_by_id('location-field-leg1-origin')
wait.until(EC.visibility_of(fieldInput))
fieldInput.send_keys("SFO")
wait.until(EC.presence_of_element_located((By.TAG_NAME, "strong")))
driver.find_element_by_tag_name('strong').click()
driver.find_elements(By.CLASS_NAME,'uitk-faux-input')[1].click()
fieldInput = driver.find_element_by_id('location-field-leg1-destination')
wait.until(EC.visibility_of(fieldInput))
fieldInput.send_keys("BOS")
wait.until(EC.presence_of_element_located((By.XPATH,"//strong[contains(text(), 'Boston')]")))
driver.find_element_by_xpath("//strong[contains(text(), 'Boston')]").click()

推荐阅读