selenium 引发属性错误:类型Object‘by’没有属性‘XPath’

798qvoo8  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(987)

我对 selenium 有问题。

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()

这是我的密码。我认为我正确地遵循了文档。尽管如此,在运行该应用程序时,我收到以下错误:

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'

我不知道我做错了什么。如果需要,我可以添加每一个可能的细节。
编辑:以下是我的导入内容:

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
vfh0ocws

vfh0ocws1#

您的代码看起来是正确的。
确保正确导入了By
应使用此导入:

from selenium.webdriver.common.by import By

相关问题