有什么方法可以用 python 捕获 selenium 请求 headers 吗?

Is there any way to capture selenium request headers with python?

我想直接使用 selenium 或通过代理从传出请求中获取授权 header。

我尝试过的方法:

  1. 使用 driver.get_log('performance') 获取请求日志 => 只有一些请求似乎被编入索引,并且 none 包含授权 header。
  2. 使用 browsermobproxy 拦截请求 => 尽管所有请求都已记录,但它没有返回 headers(headers==[],即使 headersSize==814

这是当前代码:

from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from browsermobproxy import Server

# Set configuration variables
browsermob_binary_path = r"path\to\browsermob-proxy"
facebook_credentials = {'email': 'my_email', 'password': 'my_password'}

# Configure proxy server
server = Server(browsermob_binary_path)
server.start()
proxy = server.create_proxy()

# Configure chrome to use proxy
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % proxy.proxy)
chrome_options.add_argument('--ignore-certificate-errors')

# Start chrome
driver = webdriver.Chrome(chrome_options=chrome_options)

# Start network capture
proxy.new_har('capture')

# Login to facebook
driver.get('https://apps.facebook.com/coin-master/?pid=socialfacebook')
driver.find_element_by_id("email").send_keys(facebook_credentials['email'])
driver.find_element_by_id("pass").send_keys(facebook_credentials['password'] + Keys.ENTER)

# Wait until game fully loads to make sure login request has taken place
sleep(100)

# Return all headers from captured requests
for i in range(len(proxy.har['log']['entries'])):
    print(proxy.har['log']['entries'][i]['request']['headers'])   # Always returns "[]"

# Close all dependencies
server.stop()
driver.quit()

解决方案

要在每个请求中捕获 headers,我必须替换 proxy.new_har('capture')proxy.new_har('capture', options={'captureHeaders': True})

以前 headers 被忽略,但 captureHeaders 标志强制 browsermobproxy 捕获它们。