1 .stripped_strings 方法可以得到过滤掉空格和空行的内容
2 .get_text()
如果你仅仅想要得到文档或者标签的文本部分,可以使用.get_text()方法,它能以一个单一的一个Unicode串的形式返回文档中或者Tag对象下的所有文本。
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'
你可以指定一个字符串来连接文本的位。
1 soup.get_text("|")
2 #u'\nI linked to |example.com|\n'
进一步,通过strip去除掉文本每个位的头尾空白。
1 soup.get_text("|", strip=True)
2 #u'I linked to|example.com'
用列表推导式以及.stripped_strings方法罗列出文本内容。
1 [text for text in soup.stripped_strings]
2 #[u'I linked to', u'example.com']