繁体   English   中英

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

[英]Change user-agent for Selenium web-driver

我在Python中有以下代码:

from selenium.webdriver import Firefox
from contextlib import closing

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

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

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

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

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

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

获取用户代理

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

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

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

agent变量将包含用户代理。

为了建立路易斯的有用答案......

在 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 中做到这一点,请编辑我的答案或在下面添加评论! 干杯。

这是动态更改请求 UserAgent 的简短解决方案。

使用 Chrome 更改请求的 UserAgent

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

driver = webdriver.Chrome(driver_path)
driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent":"python 2.7", "platform":"Windows"})
driver.get('http://amiunique.org')

然后返回您的用户代理:

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

一些来源

来自 SeleniumHQ 的webdriver.py的源代码( https://github.com/SeleniumHQ/selenium/blob/11c25d75bd7ed22e6172d6a2a795a1d195fb0875/py/selenium/webdriver/chrome/webdriver.py )通过 Chrome Devtools 协议扩展了它的功能

def execute_cdp_cmd(self, cmd, cmd_args):
        """
        Execute Chrome Devtools Protocol command and get returned result

我们可以使用 Chrome Devtools 协议查看器列出更多扩展功能( https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride )以及要使用的参数类型。

Firefox 配置文件已弃用,您必须在 Firefox 选项中使用它,如下所示:

opts = FirefoxOptions()
opts.add_argument("--headless")
opts.add_argument("--width=800")
opts.add_argument("--height=600")
opts.set_preference("general.useragent.override", "userAgent=Mozilla/5.0 
(iPhone; CPU iPhone OS 15_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like 
Gecko) CriOS/101.0.4951.44 Mobile/15E148 Safari/604.1")

为了建立在 JJC 的有用答案的基础上,该答案基于 Louis 的有用答案......

使用 PhantomJS 2.1.1-windows 这条线有效:

driver.execute_script("return navigator.userAgent")

如果它不起作用,您仍然可以通过日志获取用户代理(以Mma 的回答为基础):

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'])

警告:FirefoxProfile 已被删除

使用FirefoxProfile的常规方法现已弃用,您必须改用Options

如何使用选项更改 FireFox 用户代理

只需与FirefoxProfile相同,但使用Options对象,如下所示:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
agent = " Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
options.set_preference("general.useragent.override", agent)

driver = webdriver.Firefox(options=options)

使用 git 中的随机用户代理

要使用随机用户代理,您可以从这个用户代理的 git 列表中随机提取(需要pip install requests ):

import requests,random
agents = requests.get("https://gist.githubusercontent.com/pzb/b4b6f57144aea7827ae4/raw/cf847b76a142955b1410c8bcef3aabe221a63db1/user-agents.txt").text.split('\n')
agent = random.choice(agents)

使用 pip 包中的随机用户代理

通过 pip 安装有一个名为random-user-agent的有用软件包

pip install random-user-agent

然后得到一个随机代理:

from fake_useragent import UserAgent
agent = UserAgent().random

完整示例

这是使用选项为 selenium 设置随机用户代理的完整示例:

from fake_useragent import UserAgent
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.set_preference("general.useragent.override", UserAgent().random)

driver = webdriver.Firefox(options=options)

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM