子节点
一个Tag可能包含多个字符串或其它的Tag,这些都是这个Tag的子节点。Beautiful Soup提供了许多操作和遍历子节点的属性。
注意:Beautiful Soup中字符串节点不支持这些属性,因为字符串没有子节点。
tag的名字
操作文档树最简单的方法就是告诉它你想获取的tag的name。如果想获取 <head> 标签,只要用 soup.head:
print(soup.head)
# <head><title>The Dormouse's story</title></head>Code language: HTML, XML (xml)
这是个获取tag的小窍门,可以在文档树的tag中多次调用这个方法。下面的代码可以获取 <body> 标签中的第一个 <b> 标签:
print(soup.body.b)
# <b>The Dormouse's story</b>Code language: PHP (php)
通过点取属性的方式只能获得当前名字的第一个tag:
print(soup.a)
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>Code language: HTML, XML (xml)
如果想要得到所有的 <a> 标签,或是通过名字得到比一个tag更多的内容的时候,就需要用到 Searching the tree 中描述的方法,比如:find_all()
print(soup.find_all('a'))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]Code language: HTML, XML (xml)
Previous: 字符截取字符串