Python Selenium代码执行报错,求DeprecationWarning与AttributeError解决方法
解决Selenium代码中的两个报错问题
第一个报错:DeprecationWarning: executable_path has been deprecated
原因
Selenium 4.x版本起,executable_path参数已被弃用,不能直接在webdriver.Chrome()中指定驱动路径,必须通过Service对象管理驱动配置。
解决步骤
- 从
selenium.webdriver.chrome.service导入Service类 - 用
Service实例包装驱动文件路径 - 将
Service实例作为service参数传入webdriver.Chrome()
第二个报错:AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'
原因
Selenium 4.x弃用了find_element_by_xpath、find_element_by_id这类旧版元素定位方法,统一使用find_element()配合By类指定定位策略。
解决步骤
- 从
selenium.webdriver.common.by导入By类 - 将
driver.find_element_by_xpath('xxx')替换为driver.find_element(By.XPATH, 'xxx')
修正后的完整代码
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By # 配置驱动服务 service = Service("C:\\browserdrivers\\chromedriver.exe") driver = webdriver.Chrome(service=service) driver.get("https://www.aliexpress.com/item/1005004580390613.html?spm=a2g0o.search0304.0.0.2b6c66b9cAGH2z&algo_pvid=f3d04756-9c4f-4971-a2e2-c7d03e07305f&aem_p4p_detail=202207310340491186137100550600065998606&algo_exp_id=f3d04756-9c4f-4971-a2e2-c7d03e07305f-2&pdp_ext_f=%7B%22sku_id%22%3A%2212000029704251181%22%7D&pdp_npi=2%40dis%21USD%21%213.29%21%21%21%21%21%402100bdec16592640492515275ecd10%2112000029704251181%21sea") # 使用新定位方式获取元素 w = driver.find_element(By.XPATH, '//*[@id="root"]/div/div[2]/div/div[2]/div[4]/div[1]/span') # 原代码print("w")仅打印字符串,若要输出元素文本需改为print(w.text) print(w.text) # 执行完毕关闭驱动,避免资源占用 driver.quit()
内容的提问来源于stack exchange,提问作者Freak Time
相关产品推荐
相关产品推荐

