selenium设置ua
时间: 2025-02-22 17:13:12 浏览: 13
如何在 Selenium 中设置 User-Agent
为了改变浏览器发送的 HTTP 请求中的 User-Agent
字符串,在启动浏览器实例之前配置 Desired Capabilities 是必要的。对于不同的浏览器,这一过程略有不同。
Chrome 浏览器
当使用 ChromeDriver 来控制 Google Chrome 时,可以通过向 ChromeOptions 添加自定义参数来修改 User-Agent
:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"
chrome_options.add_argument(f'user-agent={user_agent}')
driver = webdriver.Chrome(options=chrome_options)
此方法允许指定任何有效的 User-Agent
值[^1]。
Firefox 浏览器
针对 Mozilla Firefox 的情况,则需利用 FirefoxProfile 或者更推荐的方式是使用 FirefoxOptions 类来进行类似的设定:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options as Firefox_Options
firefox_options = Firefox_Options()
firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("general.useragent.override",
"Mozilla/5.0 (X11; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0")
driver = webdriver.Firefox(firefox_profile=firefox_profile, options=firefox_options)
上述代码片段展示了如何覆盖默认的 User-Agent
设置[^2]。
值得注意的是,虽然 WebDriver 提供了一种更加现代化的方式来自动化 Web 应用测试,并且提供了更好的 API 设计和支持更多的特性,但是有时候仍然可能需要用到旧版本的功能,比如这里提到的不同浏览器的具体实现细节[^3]。
相关推荐



















