You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Undetected Chromedriver时找不到find_element_by_xpath方法求助

解决Undetected Chromedriver中find_element_by_xpath不存在的问题

你的报错核心原因是Selenium 4.x版本已彻底移除find_element_by_xpath这类旧的元素定位方法,Undetected Chromedriver基于Selenium开发,自然也遵循这个版本规范。

修复步骤:

  1. 导入By类用于指定定位策略
  2. 将旧的find_element_by_xpath调用替换为新的find_element()方法

修改后的完整代码:

import tempfile
import undetected_chromedriver as webdriver
import sys
import selenium
import threading
from threading import Thread
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By  # 新增导入By类
import time
from bs4 import BeautifulSoup

# 配置Chrome选项
options = webdriver.ChromeOptions()
profile = r"C:\Users\merta\AppData\Local\Google\Chrome\User Data\Default"  # 加r避免反斜杠转义问题
options.add_argument(f"user-data-dir={profile}")
browser = webdriver.Chrome(options=options, use_subprocess=True)
browser.get("https://www.hepsiburada.com/laptop-notebook-dizustu-bilgisayarlar-c-98")

# 使用新的元素定位写法
element = browser.find_element(By.XPATH, '//*[@id="oldHeader_5b475cae-5271-48a4-2ce4-e5ad94851cd0"]/div/div[1]/div[2]/ul/li[3]')

额外说明:

  • 你看到别人仍在使用find_element_by_xpath,是因为他们的环境用的是Selenium 3.x版本,该版本还保留着这些旧方法
  • 路径字符串前加r是为了避免反斜杠被解析为转义字符,防止用户目录路径读取错误

内容的提问来源于stack exchange,提问作者Mery Cel.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 17:32:45