V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
weeevv
V2EX  ›  Python

请教一个 Python 爬 bing 词典遇到的音标乱码的问题。

  •  
  •   weeevv · Jan 30, 2018 · 3642 views
    This topic created in 3020 days ago, the information mentioned may be changed or developed.
    用 HTMLParser 解析页面代码,其它部分都没问题,但是个别音标会出错。
    比如 abdication, 音标为: "美 [ˌæbdɪ'keɪʃ(ə)n] ",会被解析成"美[ˌbdɪ'ke�", 查看页面编码是 utf-8 没问题,音标行代码为:
    <div class="hd_prUS">美&nbsp;[ˌæbdɪ'keɪʃ(ə)n] </div>。

    Python 版本 2.7, 请问我是哪里出了问题?
    6 replies    2018-02-01 15:22:41 +08:00
    rabbbit
        1
    rabbbit  
       Jan 30, 2018
    把所有代码贴上来
    TimePPT
        2
    TimePPT  
    PRO
       Jan 30, 2018
    <div class="hd_prUS">美&#160;[ˌ&#230;bdɪ'keɪʃ(ə)n] </div>
    直接看页面源码,这个 div 的内容是这样的,部分字符被转义了。
    看看是不是这个原因导致的编码问题。
    记得 HTMLParser 有专门的处理方法。
    好像是这个 https://docs.python.org/2/library/htmlparser.html#HTMLParser.HTMLParser.handle_charref
    你看下。

    以及,貌似页面 head 的 meta 里也有同样信息,还好解一些,可以试试拿到。
    我用 BeautifulSoup 直接解析的,没问题(解析器用的 lxml )
    est
        3
    est  
       Jan 30, 2018 via Android
    requests 爬的?这玩意坑
    winglight2016
        4
    winglight2016  
       Jan 31, 2018
    这种音标需要字体支持吧?
    weeevv
        5
    weeevv  
    OP
       Feb 1, 2018
    谢谢楼上几倍,本科时写的代码直接拿来用了,没注意对音标部分作了长度限制导致 UTF8 编码直接被截断了----我原本想限制的是音标字符串的长度,所以产生了乱码。
    另外转义字符也没处理,导致æ在音标没有显示。
    weeevv
        6
    weeevv  
    OP
       Feb 1, 2018
    @weeevv 几倍-->几位
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3742 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 236ms · UTC 10:25 · PVG 18:25 · LAX 03:25 · JFK 06:25
    ♥ Do have faith in what you're doing.