爬虫之 利用字典推导式构造请求头

时间:2021-01-23 19:30:55

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
'''

headers = {i.split(":",1)[0]:i.split(":")[1] for i in a.split("\n")[1:-1]}

解析:

a.split("\n")[1:-1]  将原字符串切割成列表

i.split(":", 1)  根据: 只切割一次