bs4中find和findall用法
时间: 2024-05-01 15:21:58 浏览: 124
python中bs4.BeautifulSoup的基本用法
5星 · 资源好评率100%
在bs4中,find和find_all函数都是用来查找HTML/XML文档中的标签或标签集合的。
find函数用法:
```
find(name, attrs, recursive, text, **kwargs)
```
其中:
- name:要查找的标签名称,可以是字符串、正则表达式、列表、True或None
- attrs:标签属性,可以是字典、正则表达式、True或None
- recursive:是否递归查找,默认为True
- text:标签的文本内容,可以是字符串、正则表达式、True或None
- kwargs:其他搜索条件,如class_、id等
示例:
```python
from bs4 import BeautifulSoup
# 创建HTML文档
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
# 解析HTML文档
soup = BeautifulSoup(html_doc, 'html.parser')
# 查找第一个p标签
p_tag = soup.find('p')
print(p_tag)
# 查找class为story的所有p标签
p_tags = soup.find_all('p', class_='story')
print(p_tags)
```
find_all函数用法:
```
find_all(name, attrs, recursive, text, limit, **kwargs)
```
其中:
- name:要查找的标签名称,可以是字符串、正则表达式、列表、True或None
- attrs:标签属性,可以是字典、正则表达式、True或None
- recursive:是否递归查找,默认为True
- text:标签的文本内容,可以是字符串、正则表达式、True或None
- limit:限制查找结果的数量,默认为None
- kwargs:其他搜索条件,如class_、id等
示例:
```python
from bs4 import BeautifulSoup
# 创建HTML文档
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
# 解析HTML文档
soup = BeautifulSoup(html_doc, 'html.parser')
# 查找所有a标签
a_tags = soup.find_all('a')
print(a_tags)
# 查找所有class为sister的a标签,限制数量为2
a_tags = soup.find_all('a', class_='sister', limit=2)
print(a_tags)
```
总之,find和find_all函数是bs4中常用的查找标签的方法,可以根据需要使用不同的参数来满足查找的需求。
阅读全文