用Selenium-wire怎么添加请求头信息

我用requests登录后,获取到了认证信息,但是接下来的请求我不再使用requests,而是需要用Chrome或Firefox浏览器进行操作,页面中认证信息不是加在Cookie中,而是加在header的Security中(名称为Authorization),Selenium是不可以添加的,查询到Selenium-wire可以,但是不知道具体怎么用,所以请教万能的csdn。
程序是多线程的,每个线程的Authorization值是不一样的,所以别只发类似下面的不可操作的代码:

driver.request_interceptor = interceptor

img

什么原因不继续用requests

Chrome或Firefox浏览器自身有认证,你需要调整验证的位置,如果必须要使用单独的认证,那你应该把认证信息引入浏览器

selenium是没有办法直接获取请求的详细Headers,很多时候我们我们是需要提取相关的参数来做进一步使用比如token之类的,这里推荐使用一个SeleniumWire模块来达到目的 。
Selenium-wire模块介绍
Selenium-wire官方文档 安装:pip install selenium-wire 项目介绍 Selenium Wire 扩展了 Selenium 的 Python 绑定,让您可以访问浏览器发出的底层请求。 您编写代码的方式与编写 Selenium 的方式相同,但您会获得额外的 API 来检查请求和响应并动态更改它们。

Compatibilty

Python 3.6+

Selenium 3.4.0+

Chrome, Firefox and Remote Webdriver supported

获取请求headers

from seleniumwire import webdriver


def get_request_headers():
   """
   获取请求头headers详细信息
   """
   driver = webdriver.Chrome()
   driver.get('https://www.baidu.com')
   for request in driver.requests:
       print('请求headers:')
       print(request.headers)
       break
   driver.quit() 

获取响应headers

from seleniumwire import webdriver


def get_response_headers():
   """


   获取响应头headers详细信息

   """
   driver = webdriver.Chrome()
   driver.get('https://www.baidu.com')
   for request in driver.requests:
       print('响应headers:')
       print(request.response.headers)
       break
   driver.quit()

获取所有加载的url

from seleniumwire import webdriver


def get_request_headers():
   """
  获取所有加载的url


   """
   driver = webdriver.Chrome()
   driver.get('https://www.baidu.com')
   print('获取所有加载的url:')
   for request in driver.requests:
       print(request.url)
   driver.quit() 

看看伪装浏览器,然后加cookie看行不行

post或者get没有heads参数吗,加一下不可以吗

Selenium-wire官方添加请求header实例代码如下:


def interceptor(request):
    request.headers['New-Header'] = 'Some Value'

driver.request_interceptor = interceptor

# All requests will now contain New-Header

具体参考官网

用你说的seleniumwire 也可以,有用的话麻烦点个采纳哈~


from seleniumwire import webdriver  
from config import Config

options = {
    'proxy': {
        'http': 'http://127.0.0.1:9899',
        'https': 'http://127.0.0.1:9899',
        'no_proxy': 'localhost,127.0.0.1'
    }
}


def interceptor(request):
    request.headers['Authorization'] = 'SomeAuthorizationAuthorizationValue'


driver = webdriver.Chrome(seleniumwire_options=options, executable_path=Config.CHROME_DRIVER_PATH)
driver.request_interceptor = interceptor


driver.get('https://taobao.com')

img

由于驱动的是本地浏览器,本地浏览器有缓存,所以完美避免了浏览器的cookie问题。而且亲测,这种方式还可以直接解析浏览器当前网页,不需要启动新的浏览器,也就是说你可以预先登录到目标网站再运行程序。

1、右键谷歌浏览器快捷方式->属性,在路径上追加参数 --remote-debugging-port=9222。

2、双击打开浏览器
3、selenium远程模式连接浏览器并进行操作,这里测试控制浏览器打开百度。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.baidu.com")

这样就已经可以了,跟正常的selenium操作没有任何区别。