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

2015-05-16 17:31:26 +08:00
 onsfhg
#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
2450 次点击
所在节点    问与答
8 条回复
billlee
2015-05-16 18:08:26 +08:00
print(soup.title.text.decode('编码方案'))
omengye
2015-05-16 18:09:55 +08:00
soup = BeautifulSoup(response.text.encode('utf-8'))
onsfhg
2015-05-16 18:22:49 +08:00
@billlee @omengye 我之前也是试过,都不行
omengye
2015-05-16 18:54:07 +08:00
@onsfhg 用你的代码在pycharm里是没有错误的
onsfhg
2015-05-16 20:19:49 +08:00
奇怪,运行出错,修改一下在 python2.7上没出错
omengye
2015-05-16 20:44:59 +08:00
@onsfhg 这应该是一个输出的问题。如果你是在windows cmd里尝试输出utf-8,需要先将cmd代码页设置为utf-8
imn1
2015-05-16 20:50:29 +08:00
cmd + enter
chcp 65001 + enter
run...
killpanda
2015-05-16 21:11:24 +08:00
soup = BeautifulSoup(response.text, from_encoding='foo')

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/191548

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX