39 爬虫 - BeautifulSoup4搜索文档树
2023-09-11 14:15:43 时间
find_all(name, attrs, recursive, text, **kwargs)
1)name 参数
name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉
A.传字符串
最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的<b>
标签:
soup.find_all('b')
# [<b>The Dormouse's story</b>]
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>]
B.传正则表达式
如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以b开头的标签,这表示<body>
和<b>
标签都应该被找到。
import re
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
# body
# b
C.传列表
如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有<a>
标签和<b>
标签:
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>]
2)keyword 参数
soup.find_all(id='link2')
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
3)text 参数
通过 text 参数可以搜搜文档中的字符串内容,与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表
soup.find_all(text="Elsie")
# [u'Elsie']
soup.find_all(text=["Tillie", "Elsie", "Lacie"])
# [u'Elsie', u'Lacie', u'Tillie']
soup.find_all(text=re.compile("Dormouse"))
[u"The Dormouse's story", u"The Dormouse's story"]
相关文章
- Word处理控件Aspose.Words功能演示:使用 C++ 保护或取消保护 Word 文档
- Word处理控件Aspose.Words功能演示:在 C# 中从 Word 文档中提取文本
- 科普|文本分析浅析——文档分类
- 《Apache Flink 官方文档》前言
- 在linux中创建和解压文档的11个 tar 命令例子
- windows11安装rabbitmq文档
- C#使用Aspose.Words操作word文档(利用模板2)
- LazyHGrid (SwiftUI 中文文档手册)
- vue文档摘录八:指令明细
- stylus使用文档总结:选择器+变量+插值+运算符+混合书写+方法
- Java根据文档注释生成API说明文档
- CI分支kohana在线文档
- DBImport V3.1 数据互导工具及文档生成器更新发布
- Devexpress 开发思路:1看案例;2点一下看属性列表;3论坛搜索和提问;4看文档(文档大多就写个名字,没有例子);