python 爬取网页编码问题

查看:110
本文介绍了python 爬取网页编码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我在爬取凤凰网却出现
UnicodeEncodeError: 'gbk' codec can't encode character 'xa0' in position 151120: illegal multibyte sequence

这是我的代码

__author__ = 'my'
import urllib.request
url = 'http://www.ifeng.com/'
req = urllib.request.urlopen(url)
req = req.read()
req = req.decode('utf-8')
print(req)

为什么utf8却报错GBK?

解决方案

这个是 cmd.exe 的问题,别的软件都能正确解码。例如 记事本、浏览器。。。。

import urllib.request
import os
url = 'http://www.ifeng.com/'
rsp = urllib.request.urlopen(url)
body = rsp.read()
html = r'C:\ifeng.html' # 文件路径, 可以改成你自己想要的
with open(html, 'wb') as w:
    w.write(body) # 直接以 二进制 写入文件,不必解码.
os.popen('notepad.exe ' + html) # 用 记事本 打开,就可以看到内容了.


追加:
其实也可以修改cmd.exe 的编码为 utf-8(cp65001)
步骤:
1、运行CMD.exe
2、chcp 65001
3、修改窗口属性的字体
在CMD窗口标题栏上点击右键,选择"属性"->"字体",将字体修改为True Type字体"Lucida Console"
如图:

4、运行 python

x.py 的内容:

import urllib.request

url = 'http://www.ifeng.com/'
rsp = urllib.request.urlopen(url)
body = rsp.read()
html = body.decode('utf-8')
print(html[:500]) # 前500个字符
#print(html) # 也可打印全部,看看有没有错

这篇关于python 爬取网页编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆