您的位置:首页 > 编程语言 > Python开发

python-71:get_text()

2016-01-04 00:00 691 查看
上一小节我们已经实现将带有正文部分的那段源码抠出来了,我们现在要考虑的问题是怎么获取里面的文字内容。

获取文字内容前面也遇到过,.string 方法,但是这个方法只能获取单个tag的内容,如果一个tag里面还包含其他的子孙节点的话,使用.string方法会返回None,这就意味着我们需要使用另外一个方法来实现我们想要的功能,最好的情况是真的有这样一个方法。

get_text()

如果只想得到tag中包含的文本内容,那么可以嗲用 get_text() 方法,这个方法获取到tag中包含的所有文版内容包括子孙tag中的内容,并将结果作为Unicode字符串返回:
markup = '<a href="http://example.com/">\nI linked to <i>example.com</i>\n</a>'
soup = BeautifulSoup(markup)
soup.get_text()
u'\nI linked to example.com\n'
soup.i.get_text()
u'example.com'

可以通过参数指定tag的文本内容的分隔符:
# soup.get_text("|")
u'\nI linked to |example.com|\n'

还可以去除获得文本内容的前后空白:
# soup.get_text("|", strip=True)
u'I linked to|example.com'

这里的描述已经很清楚了,而且例子也是很好理解,通过文档中的这段内容,如果我们想要获取正文中的文本内容,我们需要将这句代码加入到刚才的程序中,改完之后的程序应该是这样的

#!/usr/bin/env python
# -*- coding:UTF-8 -*-
__author__ = '217小月月坑'

'''
get_text()获取文本内容
'''

import urllib2
from bs4 import BeautifulSoup

url = 'http://beautifulsoup.readthedocs.org/zh_CN/latest/#'
request = urllib2.Request(url)
response = urllib2.urlopen(request)
contents = response.read()
soup = BeautifulSoup(contents)
soup.prettify()

result = soup.find(itemprop="articleBody")
print result.get_text()

结果是这样的



这个结果比我预想的要好很多,因为我在看网页源码时,发现有很多转义字符或者什么七七八八的东西,就比如这样的<" 等等

<div class="highlight-python"><div class="highlight"><pre><span class="n">html_doc</span> <span class="o">=</span> <span class="s">"""</span>
<span class="s"><html><head><title>The Dormouse's story</title></head></span>
<span class="s"><body></span>
<span class="s"><p class="title"><b>The Dormouse's story</b></p></span>

<span class="s"><p class="story">Once upon a time there were three little sisters; and their names were</span>
<span class="s"><a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,</span>
<span class="s"><a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and</span>
<span class="s"><a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;</span>
<span class="s">and they lived at the bottom of a well.</p></span>

<span class="s"><p class="story">...</p></span>
<span class="s">"""</span>
</pre></div>

我还以为这些需要我们自己进行替换,但没想要BS4直接帮我把这些字符给转好了,但是转念一想,BS4基于HTML规则来进行分析,而这些字符也是符合HTML规则的,所以能够正常转义也没有什么奇怪的

好了获取正文的文本内容就到这里,这几个小节的体验告诉我,BS4还是很方便的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 爬虫