BeautifulSoup应用笔记(3)- 搜索文档树

过滤器

过滤器可以被用在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


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值