推荐学习书目
› 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
cloverfisher
V2EX  ›  Python

关于用PyQuery解析网页报错的问题

  •  
  •   cloverfisher · Mar 14, 2013 · 7132 views
    This topic created in 4944 days ago, the information mentioned may be changed or developed.
    用PyQuery解析一个有日文的网站,然后报错:ValueError: Unicode strings with encoding declaration are not supported.
    从http://lxml.de/parsing.html网站上得知,解析的文件在parse之前是不能用utf-8的。
    用requests抓的网页不都已经自动转成utf-8了么,原来都没有什么问题的啊,为啥会出问题呢?我用了decode encode什么的转成其他格式也不行。
    7 replies  •  1970-01-01 08:00:00 +08:00
    cloverfisher
        1
    cloverfisher  
    OP
       Mar 14, 2013
    timonwong
        2
    timonwong  
       Mar 14, 2013
    问题是网页中的这一行:
    <?xml version="1.0" encoding="UTF-8"?>
    cloverfisher
        3
    cloverfisher  
    OP
       Mar 14, 2013
    @timonwong 这一行有什么严重的问题么??真的没法解析本来就是utf-8的xml??那么如何解决这个问题呢
    for4
        4
    for4  
       Mar 14, 2013
    r = requests.get('http://cn.shindanmaker.com')
    用r.content 别用r.text
    timonwong
        5
    timonwong  
       Mar 14, 2013   ❤️ 1
    @cloverfisher
    因为是字符串是unicode类型了(转码后的了), lxml找到encoding的相关申明还会尝试转到unicode一次,自然会失败,给这些解析器的都该是raw string.

    所以请使用 @for4 介绍的 r.content
    cloverfisher
        6
    cloverfisher  
    OP
       Mar 14, 2013
    @for4 谢谢~
    cloverfisher
        7
    cloverfisher  
    OP
       Mar 14, 2013
    @timonwong 3Q :)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   996 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:10 · PVG 07:10 · LAX 16:10 · JFK 19:10
    ♥ Do have faith in what you're doing.