參考:https://blog.csdn.net/qq_39802740/article/details/89884756
前言:前些天看到一篇關於一鍵轉換爬蟲請求頭headers的博客,不過感覺代碼冗餘度有些高,經過優化並添加了一些東西的東西后寫了這篇博客
代碼:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def get_header(headers):
infos = headers.split("\n")
while "" in infos:
infos.remove("")
header = {i.split(": ")[0]: i.split(":")[1] for i in infos}
return header
def get_cookie(cookies):
infos = cookies.replace("\n", "").split("; ")
while "" in infos:
infos.remove("")
header = {i.split("=")[0]: i.split("=")[1] for i in infos}
return header
# 當字符cookie沒有換行時,可簡潔到只使用一條代碼
# return {i.split("=")[0]: i.split("=")[1] for i in cookies.split("; ")}
headers = """
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Host: blog.csdn.net
Referer: https://blog.csdn.net/qq_39802740/article/list/1?
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36
"""
cookies = """
BAIDU_SSP_lcr=http://www.guajigame.com/_menghuan/index.html; BAIDUID=1D48507710C13530E1F4DAD9C36621A3:FG=1; PSTM=1551859312
"""
a = get_header(headers)
print(a)
print(type(a))
b = get_cookie(cookies)
print(b)
print(type(b))
執行結果:
注意:(新手看)