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

设置Selenium ChromeDriver UserAgent时遇“chromedriver需在PATH中”错误求助

Fixing the "chromedriver executable needs to be in PATH" Error in Your Selenium Code

Hey there! Let's break down what's going wrong with your code and fix that frustrating WebDriverException.

The Issues in Your Current Code

  • You're creating two separate driver instances: first without any options, then again with your UserAgent configuration. The second instance doesn't get the correct chromedriver path, which triggers the error.
  • The chrome_options parameter is deprecated in newer Selenium versions—you should use options instead.
  • Your code order is off: you need to set up your ChromeOptions before initializing the WebDriver.
  • There's an unnecessary space around the = in your user-agent argument, which might cause Chrome to ignore the configuration.

Corrected Code

Here's the fixed version that addresses all these problems:

from selenium import webdriver

# Set up ChromeOptions first (no space in the user-agent argument)
options = webdriver.ChromeOptions()
options.add_argument('user-agent=Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36')

# Option 1: Use environment variable path (since you said it's configured correctly)
driver = webdriver.Chrome(options=options)

# Option 2: Explicitly specify the path if you want to avoid relying on environment variables
# chrome_path = r'C:\Users\Desktop\chromedriver_win32\chromedriver.exe'
# driver = webdriver.Chrome(executable_path=chrome_path, options=options)

Key Notes

  • By initializing the driver after setting up options, you ensure your custom UserAgent is applied right away, and you don't create unused driver instances.
  • Removing the space in user-agent=Mozilla/... ensures Chrome recognizes the argument properly—this is a tiny detail that often causes configuration issues.
  • Since you confirmed your environment variable is set up correctly, Option 1 should work smoothly. The explicit path option is just a fallback if you want full control over the chromedriver location.

内容的提问来源于stack exchange,提问作者Alan Otm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:32:35