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

Selenium报错AttributeError: type object 'By' has no attribute 'XPATH'求助

Selenium 报错:AttributeError: type object 'By' has no attribute 'XPATH'

问题描述

使用Selenium编写自动化脚本时,调用dr.find_element(By.XPATH, "...")触发属性错误,虽已导入By类且代码遵循规范,但仍无法正常运行。

相关代码

主函数代码

def main_test():
    chrome_options = Options()
    prefs = {"download.default_directory": f"{os.getcwd()}/Music"}
    chrome_options.add_argument("user-data-dir=selenium")
    chrome_options.add_experimental_option("prefs", prefs)
    dr = webdriver.Chrome(options=chrome_options, service=Service(ChromeDriverManager().install()))
    dr.get(URL)
    print(f"{selenium.__version__=}")
    dr.find_element(By.XPATH, "/html/body/div[1]/div[1]/div/div[1]/ul/li[2]/a").click()
    dr.quit()


if __name__ == '__main__':
    main_test()

导入语句

import socket
import httpcore
import re
import os
import json
import selenium
import httpx as web
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
from time import sleep

错误信息

selenium.__version__='4.6.0'
Traceback (most recent call last):
  File "/Users/andrea/Dev/Python/custom_scripts/ytchannel/main.py", line 142, in <module>
    main_test()
  File "/Users/andrea/Dev/Python/custom_scripts/ytchannel/main.py", line 137, in main_test
    dr.find_element(By.XPATH, "/html/body/div[1]/div[1]/div/div[1]/ul/li[2]/a").click()
AttributeError: type object 'By' has no attribute 'XPATH'

解决方案

问题源于属性名大小写错误:Selenium 4.x版本中,By类的XPATH属性为小写的xpath,而非大写的XPATH。

修改代码对应行即可解决:

dr.find_element(By.xpath, "/html/body/div[1]/div[1]/div/div[1]/ul/li[2]/a").click()

也可直接使用字符串常量替代By.xpath,效果一致:

dr.find_element("xpath", "/html/body/div[1]/div[1]/div/div[1]/ul/li[2]/a").click()

内容的提问来源于stack exchange,提问作者A.Fish

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:20:50