![1b799ff98c26f1379579af682b2a8f69.png](https://i-blog.csdnimg.cn/blog_migrate/904613c4a55cd595e81d621305fcc611.jpeg)
《Python 爬虫教程 bs4 美味汤 模块》《Python 爬虫教程 bs4 美味汤 模块(二)》、前两篇文章中已经介绍了我最长用的方法find、find_all、tag对象的属性和方法,这一篇文章继续学习Python的NavigableString对象。
![5520eb9a6d813bb5c1ee11458fad885e.png](https://i-blog.csdnimg.cn/blog_migrate/ed4f859cf90a53fea652ba609004db83.jpeg)
NavigableString
字符串常被包含在tag内.Beautiful Soup用 NavigableString 类来包装tag中的字符串:
from bs4 import BeautifulSoupsoup = BeautifulSoup('Extremely boldExtremely bold bak','lxml')tag = soup.b #获取第一个匹配到的tagtag.string# u'Extremely bold'type(tag.string)#
一个 NavigableString 字符串与Python中的Unicode字符串相同,并且还支持包含在 遍历文档树 和 搜索文档树 中的一些特性. 通过 unicode() 方法可以直接将 NavigableString 对象转换成Unicode字符串:
unicode_string = unicode(tag.string)unicode_string# u'Extremely bold'type(unicode_string)#
tag中包含的字符串不能编辑,但是可以被替换成其它的字符串,用 replace_with() 方法:
tag.string.replace_with("No longer bold")tag#
No longer bold
NavigableString 对象支持 遍历文档树 和 搜索文档树 中定义的大部分属性, 并非全部.尤其是,一个字符串不能包含其它内容(tag能够包含字符串或是其它tag),字符串不支持 .contents 或 .string 属性或 find() 方法.
如果想在Beautiful Soup之外使用 NavigableString 对象,需要调用 unicode() 方法,将该对象转换成普通的Unicode字符串,否则就算Beautiful Soup已方法已经执行结束,该对象的输出也会带有对象的引用地址.这样会浪费内存.
![1d40dceab639b1929e887ed3943bc0d6.png](https://i-blog.csdnimg.cn/blog_migrate/1ee2a83e8f2ebfe84defaae926ca70fd.jpeg)
strings 和 stripped_strings
如果tag中包含多个字符串,可以使用 .strings 来循环获取:
for string in soup.strings: print(repr(string))
输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容:
for string in soup.stripped_strings: print(repr(string))
全部是空格的行会被忽略掉,段首和段末的空白会被删除
![4c8f9799ef906a1fd436f71d6b120bed.png](https://i-blog.csdnimg.cn/blog_migrate/646ef91787c5e33bfcc5f06c1579a75d.jpeg)