selenium获取user-agent

发布时间 2023-05-17 15:57:19作者: CrossPython

网上找了好多资料,都是说怎么设置请求头的信息。
却没有说怎么获取由 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