过滤器
过滤器可以被用在tag的name中、节点的属性中、字符串中或它们的混合中。过滤器包括字符串、增则表达式、列表、True及方法。
字符串
会查找与字符串完整匹配的内容:
soup.find_all('b')
# [<b>The Dormouse's story</b>]
正则表达式
会通过正则表达式的match()进行匹配:
for tag in soup.find_all(re.compile("t")):
print(tag.name)
# html
# title
列表
会与列表中的任一元素进行匹配:
soup.find_all(["a", "b"])
# [<b>The Dormouse's story</b>,
# <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>]
True
匹配任何值:
for tag in soup.find_all(True):
print(tag.name)
# html
# head
# title
# body
# p
# b
# p
# a
# a
方法
方法接受一个元素参数,如果这个方法返回True,表示当前元素匹配:
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
soup.find_all(has_class_but_no_id)
# [<p class="title"><b>The Dormouse's story</b></p>,
# <p class="story">Once upon a time there were...</p>,
# <p class="story">...</p>]
搜索方法
- find_all() / find():搜索子节点
-
find_parents() / find_parent():搜索父节点
-
find_next_siblings() / find_next_sibling():搜索兄弟节点
-
find_previous_siblings() / find_previous_sibling():搜索兄弟节点
-
find_all_next() / find_next():搜索元素
-
find_all_previous() / find_previous():搜索元素
上述方法与遍历文档树中的通过属性获取的方式是对应的,如源码find_parents方法调用内部方法_find_all,传入参数parents(实际为一个生成器):
def find_parents(self, name=None, attrs={}, limit=None, **kwargs):
"""Returns the parents of this Tag that match the given
criteria."""
return self._find_all(name, attrs, None, limit, self.parents,
**kwargs)
@property
def parents(self):
i = self.parent
while i is not None:
yield i
i = i.parent