py3.11.0,初始化WebDriver 错误
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import time
# 设置ChromeDriver路径
chrome_driver_path = 'C:\chromedriver' # 请替换为你的ChromeDriver路径
# 配置ChromeOptions
chrome_options = Options()
chrome_options.add_argument("--start-maximized") # 启动时最大化窗口
chrome_options.add_argument("--disable-infobars") # 禁用信息栏
# 初始化WebDriver
service = Service(chrome_driver_path)
driver = webdriver.Chrome(service=service, options=chrome_options)
print("test")
错误提示:
Traceback (most recent call last):
File "D:\installmy\Lib\site-packages\selenium\webdriver\common\driver_finder.py", line 64, in _binary_paths
raise ValueError(f"The path is not a valid file: {path}")
ValueError: The path is not a valid file: C:\chromedriver
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\xmx-test\waigua20240905-2.py", line 17, in <module>
driver = webdriver.Chrome(service=service, options=chrome_options)
File "D:\installmy\Lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 45, in __init__
super().__init__(
File "D:\installmy\Lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 50, in __init__
if finder.get_browser_path():
File "D:\installmy\Lib\site-packages\selenium\webdriver\common\driver_finder.py", line 47, in get_browser_path
return self._binary_paths()["browser_path"]
File "D:\installmy\Lib\site-packages\selenium\webdriver\common\driver_finder.py", line 78, in _binary_paths
raise NoSuchDriverException(msg) from err
selenium.common.exceptions.NoSuchDriverException: Message: Unable to obtain driver for chrome; For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors/driver_location
感谢您提供更多的信息。看来问题是因为路径格式引起的。
为了避免Windows路径中的转义字符问题,可以使用以下两个方法之一:
1. 使用双反斜杠 `\\` 替代单反斜杠 `\`。
2. 在路径前面加上 `r`,表示原始字符串。
具体代码修改如下:
### 方法一:双反斜杠
chrome_driver_path = 'C:\\chromedriver.exe'
### 方法二:原始字符串
chrome_driver_path = r'C:\chromedriver.exe'
请确保ChromeDriver的文件名正确(一般是 `chromedriver.exe`),并在修改后重新运行代码。如果仍然有问题,请确认路径和文件名的正确性。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
|