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
Tidycc
V2EX  ›  Python

请教大家一个有关 Python3 爬虫时网页的编码问题

  •  
  •   Tidycc · 2017-07-16 23:38:00 +08:00 · 3795 次点击
    这是一个创建于 2446 天前的主题,其中的信息可能已经有所发展或是发生改变。

    今天刚入手学习 python 爬虫,用的是 python3.6。然后爬取网页时遇到一个编码的问题

    在执行以下代码时: request = urllib.request.Request(url) print(request)

    response = urllib.request.urlopen(request, timeout=20) 出现了编码的问题,错误代码为: UnicodeEncodeError: 'ascii' codec can't encode characters in position 38-39: ordinal not in range(128)

    个人觉得应该是页面中包含 Ascii 编码导致的,不知道该在哪个位置改编码。 谢谢大家

    10 条回复    2017-07-17 15:22:32 +08:00
    alvinbone88
        1
    alvinbone88  
       2017-07-17 06:39:33 +08:00
    试试在代码最前面加
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    Sylv
        2
    Sylv  
       2017-07-17 07:07:10 +08:00
    请提供具体网页 url。
    popil1987
        3
    popil1987  
       2017-07-17 08:51:52 +08:00
    request.encoding=xxx
    swordspoet
        4
    swordspoet  
       2017-07-17 09:27:05 +08:00
    这个问题我之前也遇到过,并非是“页面中包含 Ascii 编码导致的”,而是因为编译器默认的编码形式是 Ascii,一般通过添加 reload(sys)然后 setdefaultencoding('utf8')。当然在开头还要照#1 楼做。供参考
    fy
        5
    fy  
       2017-07-17 10:10:04 +08:00
    一楼四楼认真的吗?这应该是网页的编码问题,不是代码的吧。

    一个可能是都不出来(第一句错),另一个是输出不输出来(第二句错,比如 cmd 编码是 cp936,如果网页是 utf8 有些字符打不出来)。

    建议提供更多信息。另外建议使用 requests
    zhangsen1992
        6
    zhangsen1992  
       2017-07-17 10:47:32 +08:00
    requests 库多好啊 urllib 几乎没怎么用过
    w1943
        7
    w1943  
       2017-07-17 12:22:14 +08:00
    同意 5 楼,有可能是 cmd 编码和网页编码不一样
    试试 response = urllib.request.urlopen(request, timeout=20).decode('XXX')
    XXX 写你抓取网页的编码方式
    实在不行 response =unicode(urllib.request.urlopen(request, timeout=20),errors='replace')
    会自动替换编码不出来的为'0xfff',应该可以解决。
    另外推荐 requests 模块
    ivechan
        8
    ivechan  
       2017-07-17 13:05:54 +08:00
    我猜你可能用的是 CMD ?
    gulangyu
        9
    gulangyu  
       2017-07-17 14:03:21 +08:00 via Android
    你倒是把要爬的网页贴出来呀
    aidchow
        10
    aidchow  
       2017-07-17 15:22:32 +08:00 via Android
    cmd ?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5288 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 09:28 · PVG 17:28 · LAX 02:28 · JFK 05:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.