将urllib的结果,自动进行编码转化,会自动对gizp编码进行解析,或者utf-8和gbk进行编码,返回编码后的网页内容。
import urllib.request
from io import BytesIO
from http.client import HTTPResponse
import gzip
import re
def auto_charset(response: HTTPResponse):
"""
:param response: 传入响应的结果,自动进行编码转化
:return: 转化好后的网页
"""
# 查看请求头
# print(response.headers)
encoding = response.headers.get('Content-Encoding')
if encoding and "gzip" in encoding: # 如果是gzip格式,就解压转化成正常格式
f = gzip.GzipFile(fileobj=BytesIO(resp.read()))
return f.read().decode('utf-8')
elif response.headers.get("Content-Type") and 'charset' in response.headers.get(
"Content-Type"): # 如果charset在Content-type里面
# 获取网页判断,网页编码通常放在Content-Type的charset里面,获取到这个之后就知道网页采用的编码了,
# 然后就可以使用对应的编码进行解码,这里使用正则进行提取
charset = response.headers.get("Content-Type")
charset = re.search(r'charset=(.+?)(;|$)', charset).group(1)
return response.read().decode(charset)
else: # 如果charset里面没有编码,默认使用utf-8进行编码
# 提取读取获取出来的内容
text = response.read()
# 加入异常处理,如果默认UTF-8编码无法解码,则切换至GBK编码进行转化
try:
return text.decode('utf-8')
except UnicodeDecodeError as e:
return text.decode('gbk')
# 这里切换URL地址
url = 'https://www.biqooge.com/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.59',
}
# 添加请求头操作
request = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(request)
print(auto_charset(resp))