Beautiful Soup 搜索文档
html_doc = """index
首页
我常用的网站GoogleBaiduBing
...
...
"""soup = BeautifulSoup(html_doc, "lxml")
过滤器
正式讲解搜索文档之前,我们有必要了解下 Beautiful Soup 的过滤器,这些过滤器在整个搜索的 API 中都有所体现,他们可以被用在 TAG 的 name 中,属性中,字符串中或他们的混合中。听起来有点绕是么,看几个例子就懂了。
1、根据 TAG 的 name 来查找标签,下面的例子会查找文档中的所有 b 标签。同时要注意统一传入 Unicode 编码以避免 Beautiful Soup 解析编码出错。
# demo 1tags = soup.find_all('b')print(tags)#输出结果[首页]
2、如果传入正则表达式作为参数,那么 Beautiful Soup 会通过正则表达式的 match() 来匹配内容。
# demo 2import refor tag in soup.find_all(re.compile("^b")): print(tag.name)#输出结果bodyb
3、如果传入列表参数,那么 Beautiful Soup 会将与列表中任意一个元素匹配的内容返回。
# demo 3for tag in soup.find_all(['a', 'b']): print(tag)#输出结果首页GoogleBaiduBing