更改selenium驱动程序的用户代理 [英] Change user agent for selenium driver

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

问题描述

我在 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")

代理商变量将包含用户代理。

The agent variable will contain the user agent.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆