Python 爬虫 快速构建请求头headers 的方法

从network 里面获得请求头之后,如何快速构建

我们进厂要对获得的请求头转换成字典的形式,相当的麻烦,尤其是当cookie 特别长的时候 看着就头疼,这里给你一个小代码,实现半自动化构造headers ,先上代码

a = '''
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Cookie:uuid_tt_dd=1480340313111808904_20170920; Hm_lvt_6bcd52f51e9b3dce32bec4a3997715ac=1505918405; Hm_lpvt_6bcd52f51e9b3dce32bec4a3997715ac=1505918410; dc_tos=owl22x; dc_session_id=1505918405193_0.8442837642502332; __message_sys_msg_id=0; __message_gu_msg_id=0; __message_cnel_msg_id=0; __message_district_code=000000; __message_in_school=0
Host:www.csdn.net
If-Modified-Since:Wed, 20 Sep 2017 14:20:09 GMT
If-None-Match:W/"59c27919-18436"
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36
'''
b = a.strip().split('\n')
key_list =[]
value_list =[]
for i in b:
    key_list.append(i.split(':', 1)[0])
    value_list.append(i.split(':', 1)[1])
headers = {}
for i in range(len(key_list)):
    headers['{}'.format(key_list[i])] = value_list[i]

print(headers)

上面简单的意思 先通过strip 去除 a 里面头围的空格,然后用split 切片,切片的key 是回车键
切片好之后出来的是 一个列表,这个列表里面就是我headers 的每一样,那接下来的工作就是把这些列表里面的元素转换成字典的格式就行,
通过key 为‘:’ 进行切片,切1次,最好设置一下,因为有时候,cookie 里面也会有冒号 容易切多。然后分别放在key_list 和 value_list 里面,然后再通过遍历的形式,放入到dict 里面去 就可以了。最后的结果如下

D:\anaconda\python.exe D:/代码/机器学习联系.py
{'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.8', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': 'uuid_tt_dd=1480340313111808904_20170920; Hm_lvt_6bcd52f51e9b3dce32bec4a3997715ac=1505918405; Hm_lpvt_6bcd52f51e9b3dce32bec4a3997715ac=1505918410; dc_tos=owl22x; dc_session_id=1505918405193_0.8442837642502332; __message_sys_msg_id=0; __message_gu_msg_id=0; __message_cnel_msg_id=0; __message_district_code=000000; __message_in_school=0', 'Host': 'www.csdn.net', 'If-Modified-Since': 'Wed, 20 Sep 2017 14:20:09 GMT', 'If-None-Match': 'W/"59c27919-18436"', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36'}

还是相当方便的,再也不需要自己去加两点和逗号,这个真的贼烦。

你可能感兴趣的:(Python)