#Python BeautifulSoup# 文章列表 Python BeautifulSoup 简介 Python BeautifulSoup 安装 Python BeautifulSoup:根据 HTML 标签名获取元素 Python BeautifulSoup:根据 class 获取元素 Python BeautifulSoup:根据 id 获取元素 Python BeautifulSoup:使用 name 获取 HTML 标签名 Python BeautifulSoup:使用 get_text 获取 HTML 标签文本内容 Python BeautifulSoup:使用 attrs 处理 HTML 标签属性 Python BeautifulSoup:使用 decode_contents 获取 HTML 标签嵌套的 HTML 内容 Python BeautifulSoup:嵌套获取元素 Python BeautifulSoup:使用 find 和 find_all 查找元素 Python BeautifulSoup:使用 select_one 和 select 查找元素 Python BeautifulSoup:使用 append 追加内容 Python BeautifulSoup:使用 insert 插入内容 Python BeautifulSoup:使用 clear 清空内容 Python BeautifulSoup:设置内容 Python BeautifulSoup:使用 string 获取和设置 HTML 标签内容 Python BeautifulSoup:使用 extract 删除 HTML 标签 Python BeautifulSoup:使用 prettify 格式化 HTML Python BeautifulSoup:获取前后的同级元素 Python BeautifulSoup:使用 find_previous、find_next 获取当前元素前后的元素 Python BeautifulSoup:使用 find_parent 获取父元素 Python BeautifulSoup:使用 wrap 为元素增加父元素 Python BeautifulSoup 实战:去除 HTML 中的注释 Python BeautifulSoup 实战:去除 HTML 中的 script Python BeautifulSoup 实战:解析 oschina 首页内容 Python BeautifulSoup 实战:解析微信公众号文章列表 Python BeautifulSoup 实战:替换 href 属性内容

Python BeautifulSoup:根据 HTML 标签名获取元素


#Python BeautifulSoup#


使用 find_all 获取 div 元素

from bs4 import BeautifulSoup

html_content = '''
<div>测试01</div>
<p>测试02</p>
<div>测试03</div>
'''
soup = BeautifulSoup(html_content, 'html.parser')

for element in soup.find_all('div'):  # 或者 soup.find_all(name='div')
    print('元素: ', element)

执行结果:

元素:  <div>测试01</div>
元素:  <div>测试03</div>

使用 select 获取 div 元素

from bs4 import BeautifulSoup

html_content = '''
<div>测试01</div>
<p>测试02</p>
<div>测试03</div>
'''
soup = BeautifulSoup(html_content, 'html.parser')

for element in soup.select('div'):
    print('元素: ', element)

执行结果:

元素:  <div>测试01</div>
元素:  <div>测试03</div>

( 本文完 )