上一小节咱们已经实现将带有正文部分的那段源码抠出来了,咱们如今要考虑的问题是怎么获取里面的文字内容。html
获取文字内容前面也遇到过,.string 方法,可是这个方法只能获取单个tag的内容,若是一个tag里面还包含其余的子孙节点的话,使用.string方法会返回None,这就意味着咱们须要使用另一个方法来实现咱们想要的功能,最好的状况是真的有这样一个方法。python
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'
url
这里的描述已经很清楚了,并且例子也是很好理解,经过文档中的这段内容,若是咱们想要获取正文中的文本内容,咱们须要将这句代码加入到刚才的程序中,改完以后的程序应该是这样的
spa
#!/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()
结果是这样的code
这个结果比我预想的要好不少,由于我在看网页源码时,发现有不少转义字符或者什么七七八八的东西,就好比这样的<" 等等
orm
<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规则的,因此可以正常转义也没有什么奇怪的htm
好了获取正文的文本内容就到这里,这几个小节的体验告诉我,BS4仍是很方便的
three