BeautifulSoup NavigableString的深度理解

341人浏览 / 0人评论

字符串常被包含在tag内,Beautiful Soup用 NavigableString 类来包装tag中的字符串,如下代码所示:

from bs4 import BeautifulSoup
html = '''


hello world!

''' soup = BeautifulSoup(html, "lxml") tag = soup.p print(tag.string) print(type(tag.string))

获取NavigableString对象的方式有两种,有明显区别,请大家注意以下:

(1)通过Tag对象的.string属性

from bs4 import BeautifulSoup
html = '''


hello world!

''' soup = BeautifulSoup(html, "lxml") tag = soup.p print(tag.string) print(type(tag.string))

注意:此时

节点的NavigableString则为空。

(2)通过Tag对象的.children属性

from bs4 import BeautifulSoup
html = '''


hello world!

''' soup = BeautifulSoup(html, "lxml") tag = soup.p for child in tag.children: print(type(child)) print(child.string)

因为此时在计算机看来,上述的p标签内容为:

\nhello world!\n

所以,转换成BeautifulSoup对象只会的对应关系是这样的:

第一个\n对应:
hello world!对应:
第二个\n对应:

全部评论

晴天下起了小雨
2017-10-01 18:00
很喜欢,果断关注了
wjmyly7336064
2017-10-01 18:00
相当实用,赞美了
橘大佬
2017-10-01 18:00
就是有些细节再到位点就好了…