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

python中文编码问题

  •  
  •   Elwin · 2013-03-24 15:27:52 +08:00 · 3276 次点击
    这是一个创建于 4069 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在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 条回复    1970-01-01 08:00:00 +08:00
    liubo
        1
    liubo  
       2013-03-24 15:42:56 +08:00
    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  
       2013-03-24 15:54:45 +08:00
    soup('title')[0].get_text()是一unicode串,然后可以encode为各种编码
    nkliwenjian
        3
    nkliwenjian  
       2013-03-24 22:14:55 +08:00
    我只是来吐槽一下的。抛开1楼的fromEncoding不谈,只谈编程思路。
    c = urllib2.urlopen('http://tieba.baidu.com/p/2163299007')
    c是最原始的输入,如果需要编码解码的话应该是在原始输入这里来进行,跑那么后进行干嘛?
    完全可以先c.read().decode('gbk').encode('utf-8'),再放到BeautifulSoup里面去处理
    shlzs123
        4
    shlzs123  
       2013-06-20 09:23:57 +08:00
    您好,我是饿了么的招聘顾问,请问您投递的简历邮箱地址是多少?我会特别关注一下。
    Elwin
        5
    Elwin  
    OP
       2013-06-20 13:15:47 +08:00
    @shlzs123 [email protected],我大概是前天发的邮件吧:-)~
    Elwin
        6
    Elwin  
    OP
       2013-06-22 11:59:59 +08:00   ❤️ 1
    @shlzs123 有收到简历么 T T。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5662 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 09:14 · PVG 17:14 · LAX 02:14 · JFK 05:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.