soup.find_all 获取 div 中的文字
时间: 2024-02-12 14:03:02 浏览: 35
如果您想获取所有 div 标签中的文字,可以使用 BeautifulSoup 的 find_all 方法。以下是一个例子:
```python
from bs4 import BeautifulSoup
html = '''
<div class="content">
<p>Hello, World!</p>
</div>
<div class="content">
<p>How are you?</p>
</div>
'''
soup = BeautifulSoup(html, 'html.parser')
divs = soup.find_all('div', class_='content')
for div in divs:
text = div.text.strip()
print(text)
```
输出:
```
Hello, World!
How are you?
```
在这个例子中,我们首先将 HTML 代码传递给 BeautifulSoup 对象,并使用 find_all 方法查找所有 class 为 "content" 的 div 标签。然后,我们遍历每个 div 标签,并使用 text 属性获取 div 中的文字,并使用 strip 方法去掉多余的空格和换行符。
相关问题
soup.find_all 用法
`soup.find_all()` 是 Beautiful Soup 库中的一个方法,用于在 HTML 或 XML 文档中查找所有满足条件的标签。
使用方法如下:
```
soup.find_all(name, attrs, recursive, string, **kwargs)
```
参数解释如下:
- `name`: 可以是标签名,也可以是 True,表示查找所有标签。
- `attrs`: 可以是一个字典,表示查找满足某些属性条件的标签。
- `recursive`: 默认为 True,表示递归查找。若设为 False,则只查找直接子节点。
- `string`: 查找包含某些文本的标签。
- `**kwargs`: 其他可选参数,可以指定查找满足某些其他条件的标签。
使用示例:
```python
from bs4 import BeautifulSoup
html = '<html><body><div>hello</div><div>world</div></body></html>'
soup = BeautifulSoup(html, 'html.parser')
# 查找所有 div 标签
divs = soup.find_all('div')
print(divs) # 输出两个 div 标签
# 查找所有带有 class 属性的标签
class_tags = soup.find_all(attrs={'class': True})
print(class_tags) # 输出空列表,因为没有带 class 属性的标签
# 查找所有包含 hello 文本的标签
hello_tags = soup.find_all(string='hello')
print(hello_tags) # 输出一个包含 hello 文本的 div 标签
```
注意,`find_all()` 方法会返回一个列表,其中包含所有满足条
soup.find_all命令怎么使用
您可以使用BeautifulSoup库中的find_all()方法来查找HTML文档中的所有匹配项。例如,如果您想查找所有的<a>标签,您可以使用以下代码:
soup.find_all('a')
此外,您还可以使用其他参数来过滤您的搜索结果,例如class、id等。例如,如果您想查找class为"example"的所有<div>标签,您可以使用以下代码:
soup.find_all('div', class_='example')
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)