V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
huamihu
V2EX  ›  Python

关于中文网页爬虫显示乱码的问题

  •  
  •   huamihu · 2016-01-03 13:07:34 +08:00 · 3926 次点击
    这是一个创建于 3028 天前的主题,其中的信息可能已经有所发展或是发生改变。
    大家好,我在爬去一个中文网页的时候碰到了乱码的问题,试了很久都没成功,请帮我看下问题出在哪里?


    网址: http://www.duxieren.com/shanghaishuping/201511.shtml

    编码: UTF-8

    系统: windows 7

    Python 版本: 3

    目标: 爬取文章列表

    症状:能爬取,但是 print 出来之后全乱码,, 也尝试了了加 encoding = GBK 之类的参数但是无效,

    请帮我看看问题出在哪里,多谢了

    代码如下

    import requests, bs4
    web = requests.get('http://www.duxieren.com/shanghaishuping/')
    soup = bs4.BeautifulSoup(web.text,"html.parser")
    page = soup.findAll('a',{'class':'archive_article'})
    for i in page:
    print(i.get_text())
    7 条回复    2016-01-07 23:37:34 +08:00
    rudy1224
        1
    rudy1224  
       2016-01-03 13:27:26 +08:00
    第二行和第三行之间插一句
    web.encoding='utf8'
    手动指定编码
    huamihu
        2
    huamihu  
    OP
       2016-01-03 15:16:56 +08:00
    @rudy1224 谢谢,我去尝试一下
    janeyuan
        3
    janeyuan  
       2016-01-03 18:04:16 +08:00
    GBK 是 GB18030 的子集 也就是说 GBK 有些字符不能显示 推荐直接用 GB18030

    soup = BeautifulSoup(response,from_encoding='GB18030')
    links = soup.find_all("td")

    for ins in links:
    if ins.get_text()!=None:
    fout.write("<td>%s</td>"% ins.get_text().decode('GB18030').strip())
    ahxxm
        4
    ahxxm  
       2016-01-03 19:22:04 +08:00   ❤️ 1
    requests.get().text 在 python2 里是 unicode , python3 里是 str (也是 unicode ), requests 会把网页内容(.content ,类型是 bytes)用 chardet 检测出的编码类型转换成 unicode ,然后给.text 这个 property 。

    然而 windows 命令行的默认编码是 cp936 (好像是这么拼的),所以如果 chardet 抽风了, unicode 内容就不合理, print 时候就可能乱码或者报错,后者可能性更高一点。

    有两个方法: 0 )你开个文件把爬到的东西写进去,完了用 sublime/notepad++之类的东西打开看看,能看就没错了; 1 )手动给 response.content 做 decode ,我这儿 win10+python3.4.2 , rsp.content.decode('utf-8') != rsp.text

    print(web.content.decode('utf-8')),我这个 win10 能正确在 cmd 中打印网页里的中文
    ahxxm
        5
    ahxxm  
       2016-01-03 19:23:10 +08:00
    上面说得不太准,是.text 这个 property 会调用 chardet 检测并自作聪明地返回结果……
    Allianzcortex
        6
    Allianzcortex  
       2016-01-03 21:09:57 +08:00
    如果可以用 print 输出正确显示的话那么就是 unicode 编码格式的问题了,有不同的解决方法,最直接的就是用 decode 和 encode 对网页内容进行各种转换
    huamihu
        7
    huamihu  
    OP
       2016-01-07 23:37:34 +08:00
    @ahxxm 非常感谢你的帮助,
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   959 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:24 · PVG 05:24 · LAX 14:24 · JFK 17:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.