iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python Selenium WebDriver 如何设置请求头用户代理(User-Agent)参数
  • 713
分享到

Python Selenium WebDriver 如何设置请求头用户代理(User-Agent)参数

pythonseleniumfirefox 2023-09-05 05:09:45 713人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

在本文中,将演示如何为浏览器设置用户代理,以及如何在python selenium WEBDriver中读取用户代理。测试中的许多方案都需要操作用户代理。 什么是用户代理? User-Agent 请求

在本文中,将演示如何为浏览器设置用户代理,以及如何在python selenium WEBDriver中读取用户代理。测试中的许多方案都需要操作用户代理。

什么是用户代理?

User-Agent 请求标头包含一个特征字符串,该字符串允许网络协议对等方标识请求软件用户代理的应用程序类型、操作系统、软件供应商或软件版本。它显示在 Http 请求标头中,不适用于响应标头。所有浏览器都支持它。

简而言之,用户代理是客户端(用户)的身份。

用户代理的通过格式:

User-Agent: Mozilla/ ()  () 

Example:

Mozilla/5.0 (windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:63.0) Gecko/20100101 Firefox/63.0

Selenium 没有实现任何直接方法来读取请求或响应标头。

注意:要运行以下示例,您需要在 PATH 环境变量中设置浏览器驱动程序路径详细信息,或者在创建浏览器实例时必须将浏览器驱动程序路径传递给executable_path变量。

获取用户代理值

Selenium没有任何直接的方法可以从WebDriver实例查询用户代理。我们需要使用执行javascript内置方法来执行此操作,并传递返回user-agent的脚本。

浏览器启动后,我们可以通过执行以下代码行来获取用户代理

# Store it in a variable and print the valueagent = driver.execute_script("return navigator.userAgent")print(agent)# directly print the valueprint(driver.execute_script("return navigator.userAgent"))

Firefox 中的用户代理设置:

要更改 Firefox 浏览器的用户代理,请在 Firefox 配置文件中设置变量“general.useragent.override”,并在创建 Firefox WebDriver 实例时使用此配置文件。

from selenium import webdriverprofile = webdriver.FirefoxProfile()profile.set_preference("general.useragent.override", "[user-agent string]")# Below is tested line# profile.set_preference("general.useragent.override", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:63.0) Gecko/20100101 Firefox/63.0")driver = webdriver.Firefox(profile)

Chrome 中的用户代理设置:

在 Chrome 中,必须使用Options 对象来设置用户代理值。

from selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsopts = Options()opts.add_argument("user-agent=[user-agent string]")# Below is tested line# opts.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/71.0.3578.98 Safari/537.36")driver = webdriver.Chrome(chrome_options=opts)

Alternative way to pass driver path along with other details:
可选地,在传递驱动路径时,同时传递其它数据,如下

driver = webdriver.Firefox(profile, executable_path="path to geckodriver")
driver = webdriver.Chrome(chrome_options=opts, executable_path="path to chromedriver")

注:没有编写用户代理字符串的标准方式; 不同的Web浏览器使用不同的格式(有些格式大不相同),并且许多Web浏览器在其用户代理数据中添加了大量信息。

来源地址:https://blog.csdn.net/captain5339/article/details/131115158

--结束END--

本文标题: Python Selenium WebDriver 如何设置请求头用户代理(User-Agent)参数

本文链接: https://www.lsjlt.com/news/394752.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作