更改Selenium Web驱动程序的用户代理 [英] Change user-agent for Selenium web-driver

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

问题描述

我在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".请注意,这与硒无关.

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命令行选项.再次,这不是硒的事情.您可以在命令行中使用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 Web驱动程序的用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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