更改selenium驱动程序的用户代理

问题描述 投票:53回答:3

我在Python中有以下代码:

from selenium.webdriver import Firefox
from contextlib import closing

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

我想打印用户代理HTTP标头,并可能更改它。可能吗?

python selenium http-headers user-agent
3个回答
99
投票

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

Setting the User Agent in Firefox

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

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

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

Setting the User Agent in Chrome

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

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

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)

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

Getting the User Agent

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

但是,启动浏览器后,您可以通过执行以下命令获取用户代理:

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

agent变量将包含用户代理。


14
投票

以路易斯的有用答案为基础......

Setting the User Agent in PhantomJS

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
...
caps = DesiredCapabilities.PHANTOMJS
caps["phantomjs.page.settings.userAgent"] = "whatever you want"
driver = webdriver.PhantomJS(desired_capabilities=caps)

唯一的小问题是,与Firefox和Chrome不同,这不会返回您的自定义设置:

driver.execute_script("return navigator.userAgent")

所以,如果有人在PhantomJS中弄清楚如何做到这一点,请编辑我的答案或在下面添加评论!干杯。


0
投票

以JJC的有用答案为基础,以路易斯的有用答案为基础......

使用PhantomJS 2.1.1-windows,这条线可以工作:

driver.execute_script("return navigator.userAgent")

如果它不起作用,您仍然可以通过日志获取用户代理(在Mma's answer上构建):

from selenium import webdriver
import json
from fake_useragent import UserAgent

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (UserAgent().random)
driver = webdriver.PhantomJS(executable_path=r"your_path", desired_capabilities=dcap)
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('user agent: ', har['log']['entries'][0]['request']['headers'][1]['value'])
© www.soinside.com 2019 - 2024. All rights reserved.