python库之BeautifulSoup使用教程

安装BeautifulSoup

bash 复制代码
pip install beautifulsoup4

基本使用

python 复制代码
from bs4 import BeautifulSoup
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')

删除标签、属性

python 复制代码
# 删除标签
for i in ['style','video']:
    [s.extract() for s in soup(i)]

# 删除标签的属性
for element in soup.select('img'):
    del element['srcset']
for element in soup.select('a'):
    del element['href']

# 删除标签为div,属性class为abc的所有标签
remove_list = soup.find_all('div', attrs={'class': 'abc'})
[i.extract() for i in remove_list]

寻找标签

python 复制代码
div1 = soup.find('div', id='me')     # 只匹配第一个
div1 = soup.find_all('div', attrs={'class': 'abc'})     # 匹配出所有

删除标签,但保留其子标签且位置不变

python 复制代码
from bs4 import BeautifulSoup

html = '''
<html>
  <body>
    <div id="container">
    <p>This is a one</p>
      <div id="remove-me">
        <span>Child 1<a>111</a></span>
        <span>Child 2</span>
      </div>
      <p>This is a two</p>
    </div>
  </body>
</html>
'''
soup = BeautifulSoup(html, 'lxml')
# 找到要删除的 div 标签
div_to_remove = soup.find('div', id='remove-me')
if div_to_remove:
    # 获取父标签
    parent = div_to_remove.parent
    siblings = parent.contents
    position = siblings.index(div_to_remove)
    # 将子标签移动到父标签中
    while div_to_remove.contents:
        parent.insert(position,div_to_remove.contents[-1])
    # 删除原始标签
    div_to_remove.decompose()
# 打印结果
print(soup.prettify())
相关推荐
子兮曰2 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰2 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
前端小万2 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝2 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
三十而立洋2 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python