多语言展示
当前在线:1959今日阅读:27今日分享:41

非unicode网页的python处理办法

网页编码为unicode时,Python会把内容识别为utf-8因而导致乱码。
工具/原料

python3(本文中选用最新的3.7)

方法/步骤
1

用python抓取数据时,又是会碰到结果乱码的情况。这是由于结果以bytes的形式显示。所以我们需要将结果编码。

2

输入以下代码。from urllib.parse import quoteimport urllib.requesturl = 'http://wthrcdn.etouch.cn/weather_mini?citykey=1'content = urllib.request.urlopen(url)weather = content.read()# weather = weather.decode('utf-8', 'ignore')print(weather)

3

运行结果以b开头,举例如下b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x00\xbd\x93\xcfK\x02A\x14\xc7\xff\x95\x9a\xb3\xc1\xaeZ\x96H……

4

用decode()将字符串编码。代码修改为如下情况from urllib.parse import quoteimport urllib.requesturl = 'http://wthrcdn.etouch.cn/weather_mini?citykey=1'content = urllib.request.urlopen(url)weather = content.read()# weather = weather.decode('utf-8', 'ignore')print(weather)

5

结果显示正确,详情如下:{'data':{'yesterday':{'date':'22日星期四','high':'高温 8℃','fx':'南风','low':'低温 -3℃','fl':'','type':'晴'},'city':'北京','aqi':'110','forecast':[{'date':'23日星期五','high':'高温 7℃','fengli':'','low':'低温 0℃','fengxiang':'东北风','type':'多云'},{'date':'24日星期六','high':'高温 9℃','fengli':'','low':'低温 -3℃','fengxiang':'西南风','type':'晴'},{'date':'25日星期天','high':'高温 10℃','fengli':'','low':'低温 -3℃','fengxiang':'西南风','type':'晴'},{'date':'26日星期一','high':'高温 10℃','fengli':'','low':'低温 -1℃','fengxiang':'西风','type':'多云'},{'date':'27日星期二','high':'高温 7℃','fengli':'','low':'低温 -4℃','fengxiang':'南风','type':'晴'}],'ganmao':'天气较凉,较易发生感冒,请适当增加衣服。体质较弱的朋友尤其应该注意防护。','wendu':'4'},'status':1000,'desc':'OK'}

注意事项
1

如果您觉得我的经验帮助到了您,请帮助在下方点击投票或者赞;

2

如果您觉得我的经验没有帮助到了您,欢迎在下方提问。

推荐信息