字符串常被包含在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对应:
关注微信公众号获取更多VSCode编程信息,定时发布干货文章
全部评论