爬虫时,为了防止headers身份验证的限制,通常会将Chrome中的Request Headers
拿过来转化成需要的headers的字典格式,直接上代码
s = '''
:method: POST
:scheme: https
accept: application/json
accept-encoding: gzip, deflate, br
accept-language: zh-CN,zh;q=0.9
cache-control: no-cache
content-length: 97
user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
'''
def get_headers(h_str):
# 将字符串按行切割
li = [header.strip() for header in h_str.splitlines() if header.strip()]
# 将字符串按行分隔,并去掉将":"开头的字符的":"
s_li = [i[1:] if i.startswith(':') else i for i in li]
headers = {}
# 将列表转换成headers格式
for i in s_li:
key, value = i.split(':', 1)
# 去除复制过来request headers中的空格
headers[key.strip()] = value.strip()
return headers
注意上面有的headers是以’:'开头的,因为用的http协议不同,可以通过以下方式查看(图片中标红部分)
如果没有protocol
这一栏,通过右击请求,勾选查看即可
可以看到使用h2协议的请求request headers带有类似:method: GET
格式
使用requests请求时,如果抓取的请求遵循的是h2,其headers可以有两种处理方式:
第一种直接将’:'除去,参考上面代码
第二种通过pip install hyper安装hyper模块,安装时如果速度过慢,可以使用国内镜像:
清华:https://pypi.tuna.tsinghua.edu.cn/simple
通过hyper的HTTP20Adapter类去解决
import requests
from hyper.contrib import HTTP20Adapter
headers = {
':authority': 'h5.dianping.com',
':method': 'POST',
':scheme': 'https'
}
session = requests.session()
session.mount('http://www.dianping.com/', HTTP20Adapter())
resp = session.get('http://www.dianping.com/xxx',headers=headers)
两种方法都可以