更改 Selenium 网络驱动程序的用户代理

Change user-agent for Selenium web-driver(更改 Selenium 网络驱动程序的用户代理)

本文介绍了更改 Selenium 网络驱动程序的用户代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中有以下代码:

I have the following code in Python:

from selenium.webdriver import Firefox
from contextlib import closing

with closing(Firefox()) as browser:
  browser.get(url)

我想打印用户代理 HTTP 标头和可能会改变它.有可能吗?

I would like to print the user-agent HTTP header and possibly change it. Is it possible?

推荐答案

Selenium 无法读取请求或响应标头.您可以通过指示您的浏览器通过记录此类信息的代理进行连接来做到这一点.

There is no way in Selenium to read the request or response headers. You could do it by instructing your browser to connect through a proxy that records this kind of information.

更改 Firefox 用户代理的常用方法是在 Firefox 配置文件中设置变量 "general.useragent.override".请注意,这与 Selenium 无关.

The usual way to change the user agent for Firefox is to set the variable "general.useragent.override" in your Firefox profile. Note that this is independent from Selenium.

您可以指示 Selenium 使用与默认配置不同的配置文件,如下所示:

You can direct Selenium to use a profile different from the default one, like this:

from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "whatever you want")
driver = webdriver.Firefox(profile)

在 Chrome 中设置用户代理

对于 Chrome,您要做的是使用 user-agent 命令行选项.同样,这不是 Selenium 的事情.您可以使用 chrome --user-agent=foo 在命令行调用 Chrome 以将代理设置为值 foo.

Setting the User Agent in Chrome

With Chrome, what you want to do is use the user-agent command line option. Again, this is not a Selenium thing. You can invoke Chrome at the command line with chrome --user-agent=foo to set the agent to the value foo.

使用 Selenium,您可以这样设置:

With Selenium you set it like this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("user-agent=whatever you want")

driver = webdriver.Chrome(chrome_options=opts)

上述两种方法都经过测试,发现有效.其他浏览器我不知道.

Both methods above were tested and found to work. I don't know about other browsers.

Selenium 没有从 WebDriver 实例查询用户代理的方法.即使在 Firefox 的情况下,您也无法通过检查 general.useragent.override 如果未设置为自定义值来发现默认用户代理.(此设置在设置为某个值之前不存在.)

Selenium does not have methods to query the user agent from an instance of WebDriver. Even in the case of Firefox, you cannot discover the default user agent by checking what general.useragent.override would be if not set to a custom value. (This setting does not exist before it is set to some value.)

不过,一旦浏览器启动,您可以通过执行以下命令获取用户代理:

Once the browser is started, however, you can get the user agent by executing:

agent = driver.execute_script("return navigator.userAgent")

agent 变量将包含用户代理.

The agent variable will contain the user agent.

这篇关于更改 Selenium 网络驱动程序的用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:更改 Selenium 网络驱动程序的用户代理

基础教程推荐