新手做爬虫, list 结构如何 encode 输出能看的中文字? 如何破?

2018-08-05 12:45:59 +08:00
 pppguest3962

同一个页面,在 pycharm 的输出区,soup.title 是能看的中文字。。。 soup.select 检索到的内容,是\u661f\u671f\u65e5\xa0\xa0 这样的乱码。。。 在网上找这个问题,得到到原因(这个也是网文作者臆测吧?我自己没有能力核实)是因为 BeautifulSoup 在处理问题的时候,都是 UTF-8 视之,

第一问题: 既然 BeautifulSoup 全是 UTF8 一刀切,那么我又搞不懂为什么 title()可以正常输出中文??

按照网上攻略套路,那么我必须得把 select()方法的内容 encode 成 GBK 或者 GB2312, 按目前我的理解,BeautifulSoup 处理的方法,返回的是 list 结构而不是 str

这里问题来了,我见到网上的例子,结构居然可以用 encode(),为啥我的 pycharm + py 2.7 不行,没 encode 方法? 传送门: https://www.jianshu.com/p/69401b84419e https://www.jb51.net/article/49220.htm 这两个文章是不是在害人?

page_req = requests.get(url,headers=headers)
soup = BeautifulSoup(page_req.text,'html.parser')
print(soup.title)
#title 输出正常
print(soup.select('.fl.ps'))
#select()输出的是\u661f\u671f\u65e5\xa0\xa0,UTF8 编码
2922 次点击
所在节点    Python
9 条回复
MikePerfect
2018-08-05 13:28:16 +08:00
你确定你的第一行加入了#utf-8 的标志吗
zyqf
2018-08-05 13:48:11 +08:00
Python 3
ClutchBear
2018-08-05 16:21:07 +08:00
page_req.encoding = page_req.apparent_encoding
在 soup 那一行之前加一行这个.
ipwx
2018-08-05 16:49:59 +08:00
print 一个 list,会被 repr,不是很自然嘛?

你就不能把 select 出来的结果遍历一下嘛?
Sylv
2018-08-05 16:52:31 +08:00
不不不,这个问题和编码什么的没有关系。这个问题的实质是:Python 2 在 print list 等容器数据时,输出的是内部元素的 __repr__ 值,而不是 __str__ 值。

>>> print('你好'.__str__())
你好
>>> print('你好'.__repr__())
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print(['你好'])
['\xe4\xbd\xa0\xe5\xa5\xbd']
>>> print(['你好'][0])
你好
>>> '你好' == '\xe4\xbd\xa0\xe5\xa5\xbd'
True
>>> ['你好'] == ['\xe4\xbd\xa0\xe5\xa5\xbd']
True

所以 '\xe4\xbd\xa0\xe5\xa5\xbd' 并不是乱码,它和 '你好' 是等价的,只是表示形式的不同,前者是给解释器看的,后者是给人看的。至于 print(['你好']) 为什么要显示成 ['\xe4\xbd\xa0\xe5\xa5\xbd'] 而不是 ['你好'],其实没啥为什么,Python 2 就是这样设计的。

那我想显示 list 里的中文怎么办?

方法一:
改用 Python 3。
>>> print(['你', '好'])
['你', '好']

方法二:
>>> for i in ['你', '好']:
... print(i)



方法三:
>>> import json
>>> print(json.dumps(['你', '好'], ensure_ascii=False))
["你", "好"]

方法四:
https://stackoverflow.com/a/45841899
aaa5838769
2018-08-06 08:49:03 +08:00
为什么不使用 Python3
cxxcoding
2018-08-06 09:49:03 +08:00
为什么不使用 Python3

看我主页
talen666
2018-08-06 09:51:48 +08:00
新手还拿旧版本练手。。。
jamwong9
2018-08-06 11:31:27 +08:00
python3

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

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

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

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

© 2021 V2EX