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

python中文编码问题

  •  
  •   Elwin · Mar 24, 2013 · 3970 views
    This topic created in 4788 days ago, the information mentioned may be changed or developed.
    在ubuntu下使用python,目标是用beautifulsoup抓取百度贴吧的一个链接,获取它的title然后打印出来。现在的问题是百度的编码是gbk,我用如下代码:
    c = urllib2.urlopen('http://tieba.baidu.com/p/2163299007')
    soup = BeautifulSoup(c.read)
    title = soup('title')[0].string
    str = title.decode('gbk').encode('utf-8')
    print str
    结果输出的还是乱码,大家有什么想法么。。
    6 replies    1970-01-01 08:00:00 +08:00
    liubo
        1
    liubo  
       Mar 24, 2013
    c = urllib2.urlopen('http://tieba.baidu.com/p/2163299007').read()
    soup = BeautifulSoup(c,fromEncoding="gbk")
    title = soup('title')[0].string
    print title
    polythene
        2
    polythene  
       Mar 24, 2013
    soup('title')[0].get_text()是一unicode串,然后可以encode为各种编码
    nkliwenjian
        3
    nkliwenjian  
       Mar 24, 2013
    我只是来吐槽一下的。抛开1楼的fromEncoding不谈,只谈编程思路。
    c = urllib2.urlopen('http://tieba.baidu.com/p/2163299007')
    c是最原始的输入,如果需要编码解码的话应该是在原始输入这里来进行,跑那么后进行干嘛?
    完全可以先c.read().decode('gbk').encode('utf-8'),再放到BeautifulSoup里面去处理
    shlzs123
        4
    shlzs123  
       Jun 20, 2013
    您好,我是饿了么的招聘顾问,请问您投递的简历邮箱地址是多少?我会特别关注一下。
    Elwin
        5
    Elwin  
    OP
       Jun 20, 2013
    @shlzs123 [email protected],我大概是前天发的邮件吧:-)~
    Elwin
        6
    Elwin  
    OP
       Jun 22, 2013   ❤️ 1
    @shlzs123 有收到简历么 T T。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2527 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 126ms · UTC 02:36 · PVG 10:36 · LAX 19:36 · JFK 22:36
    ♥ Do have faith in what you're doing.