使用Selenium填写Uber表单报错WebDriver无get_element_by_xpath属性如何解决
报错原因
首先Selenium全版本都不存在get_element_by_xpath这个方法,旧版本Selenium(3.x及以下)对应的方法为find_element_by_xpath;其次你使用的如果是Selenium 4.0及以上版本,该版本已经彻底移除了所有find_element_by_*这类直接通过定位方式命名的方法,所以会触发属性不存在的报错。同时你的代码还存在几处可修复的问题,按照以下步骤调整即可:
修复步骤
- 首先导入定位方式工具类
By,以及Selenium 4推荐的Service类用于指定驱动路径,同时不要漏导入time模块 - 将调用元素的方法替换为统一的
find_element(),第一个参数传入By.XPATH,第二个参数传入你的XPath表达式 - 修正XPath的引号嵌套错误,同时替换已经过时的
executable_path、chrome_options参数写法
修正后的完整代码
import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By options = Options() options.add_argument("user-data-dir=C:\\Users\\Zedas\\AppData\\Local\\Google\\Chrome\\User Data") # 用Service指定chromedriver路径,替代过时的executable_path参数 service = Service(executable_path='chromedriver.exe') w = webdriver.Chrome(service=service, options=options) w.get("https://m.uber.com/looking") time.sleep(6) # 替换为正确的元素定位写法,同时修正XPath引号问题 w.find_element(By.XPATH, '//*[@id="booking-experience-container"]/div/div[3]/div[2]/div/input').send_keys("test")
其他优化建议
如果想要代码稳定性更高,可以把固定等待time.sleep(6)替换为显式等待,定位到元素加载完成后再执行输入操作,避免网络波动导致元素未加载完成报错。
内容的提问来源于stack exchange,提问作者Sainita
相关产品推荐
相关产品推荐

