V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
onsfhg
V2EX  ›  问与答

帮我看一下 python3 爬虫代码哪里出错了?提示编码错误。

  •  
  •   onsfhg · 2015-05-16 17:31:26 +08:00 · 2399 次点击
    这是一个创建于 3274 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #coding=utf-8
    import requests
    from bs4 import BeautifulSoup
    page = 1
    url = 'http://www.v2ex.com/recent?p=' + str(page)
    print(url)
    response = requests.get(url)
    soup = BeautifulSoup(response.text)
    print(soup.title.text)


    Traceback (most recent call last):
    File "lasttest.py", line 9, in <module>
    print(soup.title.text)
    UnicodeEncodeError: 'gbk' codec can' encode character
    8 条回复    2015-05-16 21:11:24 +08:00
    billlee
        1
    billlee  
       2015-05-16 18:08:26 +08:00
    print(soup.title.text.decode('编码方案'))
    omengye
        2
    omengye  
       2015-05-16 18:09:55 +08:00
    soup = BeautifulSoup(response.text.encode('utf-8'))
    onsfhg
        3
    onsfhg  
    OP
       2015-05-16 18:22:49 +08:00
    @billlee @omengye 我之前也是试过,都不行
    omengye
        4
    omengye  
       2015-05-16 18:54:07 +08:00
    @onsfhg 用你的代码在pycharm里是没有错误的
    onsfhg
        5
    onsfhg  
    OP
       2015-05-16 20:19:49 +08:00
    奇怪,运行出错,修改一下在 python2.7上没出错
    omengye
        6
    omengye  
       2015-05-16 20:44:59 +08:00
    @onsfhg 这应该是一个输出的问题。如果你是在windows cmd里尝试输出utf-8,需要先将cmd代码页设置为utf-8
    imn1
        7
    imn1  
       2015-05-16 20:50:29 +08:00
    cmd + enter
    chcp 65001 + enter
    run...
    killpanda
        8
    killpanda  
       2015-05-16 21:11:24 +08:00 via iPhone
    soup = BeautifulSoup(response.text, from_encoding='foo')
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2213 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 09:59 · PVG 17:59 · LAX 02:59 · JFK 05:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.