BS4 中的 NavigableString 对象,怎么将内容怎么获取并且保存,为什么我已保存就是 Unicode 乱码?

2016-10-08 21:45:51 +08:00
 scott123

BS4 中的 NavigableString 对象,怎么将内容怎么获取并且保存,为什么我已保存就是 Unicode 乱码?

url = 'http://www.xinshipu.com/zuofa/49391'
req = requests.get(url, headers=head)
soup = BeautifulSoup(req.text, 'lxml')
title = soup.select('.re-up h1')[0].text
source = soup.select('.dd')[0].text
runbook=[]
for child in soup.select('.dd')[1].children:
    if len(child.string) > 10:
        print child
        print type(child.string)
        print child.string

输出是:

</p>
<class 'bs4.element.NavigableString'>
1.将甜豆洗净、去蒂,汆烫熟备用;萝卜婴洗净,泡水备用。
</p>
<class 'bs4.element.NavigableString'>
2.鲜虾洗净去肠泥,用竹签从虾尾部分沿背瘠贯串,放入热水中汆烫熟后,再取出竹签,去头去尾,剥除壳备用。
<p>3.将寿司饭盛入容器内,再将全部材料依喜好摆放在饭上即可,搭配酱油与山葵酱一起食用。</p>
<class 'bs4.element.NavigableString'>

for 循环中使用 runbook.append(child.string) 显示为乱码 [u'1.\u5c06\u751c\u8c46\u6d17\u51c0\u3001\u53bb\u8482\uff0c\u6c46\u70eb\u719f\u5907\u7528\uff1b\u841d\u535c\u5a74\u6d17\u51c0\uff0c\u6ce1\u6c34\u5907\u7528\u3002\r']

10201 次点击
所在节点    Python
6 条回复
276562578
2016-10-08 21:48:26 +08:00
用 content 代替 text
第一号标明# *-* coding:utf-8 *-*
scott123
2016-10-08 22:11:08 +08:00
@276562578 只是部分代码,另外 content 不对。
276562578
2016-10-09 10:41:58 +08:00
@scott123 decode,encode 试试
276562578
2016-10-09 10:44:01 +08:00
@scott123 用 content 而不用 text 因为他更优秀,可以识别 html 的编码还是什么的,网上有介绍。
xarrow
2016-10-09 15:39:33 +08:00
scott123
2016-10-09 21:55:58 +08:00
@xarrow 正解!

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

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

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

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

© 2021 V2EX