首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[Python] 解析乱码HTML并转换为UTF-8编码

[Python] 解析乱码HTML并转换为UTF-8编码

作者头像
kr
发布2022-11-30 10:50:52
7.7K0
发布2022-11-30 10:50:52
举报
文章被收录于专栏:个人教程个人教程

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

通过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,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档