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

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

  •  
  •   scott123 · 2016-10-08 21:45:51 +08:00 · 10155 次点击
    这是一个创建于 2763 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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']

    6 条回复    2016-10-09 21:55:58 +08:00
    276562578
        1
    276562578  
       2016-10-08 21:48:26 +08:00 via Android
    用 content 代替 text
    第一号标明# *-* coding:utf-8 *-*
    scott123
        2
    scott123  
    OP
       2016-10-08 22:11:08 +08:00
    @276562578 只是部分代码,另外 content 不对。
    276562578
        3
    276562578  
       2016-10-09 10:41:58 +08:00 via Android
    @scott123 decode,encode 试试
    276562578
        4
    276562578  
       2016-10-09 10:44:01 +08:00 via Android
    @scott123 用 content 而不用 text 因为他更优秀,可以识别 html 的编码还是什么的,网上有介绍。
    xarrow
        5
    xarrow  
       2016-10-09 15:39:33 +08:00
    scott123
        6
    scott123  
    OP
       2016-10-09 21:55:58 +08:00
    @xarrow 正解!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   832 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 19:32 · PVG 03:32 · LAX 12:32 · JFK 15:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.