python - 使用 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
解决方案
这是一种稍微不同的定位方法。我在这个线程中使用从 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()
推荐阅读
- sql - SQL 选择字符左侧的所有内容
- xcode - 试图让谷歌地图在 React Native 中与 IOS 模拟器一起工作
- spring-boot - 将 db url 键入为 localhost 是否比提供远程服务器地址更快?
- r - ggplot 操纵轴边距
- python - 如何从python中的巨大字符串中提取子字符串?
- java - 如何按照说明显示两个数组
- maven - 可执行配置在 Maven 插件中不起作用
- r - R packrat 快照:升级包给出“陈旧”错误
- pip - 应用程序启动错误 Jupyter 笔记本
- vba - 如何在 VBA 文档的每个段落中搜索术语的第一个实例?