python + selenium 获取请求头 User-Agent 信息

网上找了好多资料,都是说怎么设置请求头的信息。
却没有说怎么获取由 selenium 提交的请求头。
尝试了好久,总结了一个办法,下面上代码:

from selenium import webdriver

driver_path = r'F:\driver\chromedriver.exe'    # 这是chrome驱动路径

# 自定义代理IP 及 请求头。
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument("--proxy-server=http://218.93.119.165:9002")  
chromeOptions.add_argument('user-agent="Mozilla/5.0 (iPod; U; CPU iPhone OS 2_1 \
                            like Mac OS X; ja-jp) AppleWebKit/525.18.1 (KHTML, like \
                            Gecko) Version/3.1.1 Mobile/5F137 Safari/525.20"')
                            
browser = webdriver.Chrome(executable_path=driver_path, chrome_options=chromeOptions)
# 新版本selenium,建议使用options替代chrome_options,如下。
# browser = webdriver.Chrome(executable_path=driver_path, options=chromeOptions)

browser.get("http://httpbin.org/ip")    # 查看IP是否切换。
print(browser.page_source)

# 获取请求头信息
agent = browser.execute_script("return navigator.userAgent")    
print(agent)   # 查看请求头是否更改。

下面方法,在之前的chrome版本中可行,现已失效。

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

# 设置变量url,用于浏览器访问。
url = 'https://www.baidu.com/'

# 关键步骤 1:下面两行代码是用来设置特性,获取request的信息前提步骤。
d = DesiredCapabilities.CHROME
d['loggingPrefs'] = {'performance': 'ALL'}


path = 'D:\work\chromedriver.exe'
browser = webdriver.Chrome(executable_path=path)

# 打开浏览器并访问网址
browser.get(url)

# 关键步骤2:获取 request 信息。
info = browser.get_log('performance')    # 这里的参数 'performance' 是步骤1中添加的。获取到的是一个列表。

# 用 for循环读取列表中的每一项元素。每个元素都是 json 格式。
for i in info:
    dic_info = json.loads(i["message"])    # 把json格式转成字典。
    info = dic_info["message"]['params']    # request 信息,在字典的 键 ["message"]['params'] 中。
    if 'request' in info:    				# 如果找到了 request 信息,就终断循环。
        print(info['request'])
        break

获取到的结果为:

{'headers': {'Upgrade-Insecure-Requests': '1',
 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36'}, 
 'initialPriority': 'VeryHigh',
 'method': 'GET',
 'mixedContentType': 'none', 
 'referrerPolicy': 'no-referrer-when-downgrade',
 'url': 'https://www.baidu.com/'}
  • 7
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值