请求网页并读取其字节数组数据。

通过chardet.detect()探查网页编码。

使用decode()encode()解码后重新编码为UTF-8格式并保存。

代码

import chardet
from urllib.request import urlopen

# 网址
url = ""

# 请求网页
response=urlopen(url,timeout=3)
html_byte=response.read()

# 读取网页编码类型
chardit1 = chardet.detect(html_byte)
print("编码: "+chardit1['encoding'])
print("语言: "+chardit1['language'])

# 显示正确解码后的网页数据
# print(html_byte.decode(chardit1['encoding']))

# 写入文件
file = open('index.html', 'wb')
html_string=html_byte.decode(chardit1['encoding']).encode('utf-8')
file.write(html_string)
file.close()
最后修改:2022 年 11 月 24 日
如果觉得我的文章对你有用,请随意赞赏