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())
相关推荐
xingyuzhisuan2 分钟前
Jupyter Notebook 云GPU配置全解析(含实操+选型指南)
ide·python·jupyter·gpu算力
ITIRONMAN9 分钟前
开源data-compare:轻量级数据对比工具
人工智能·python
云姜.21 分钟前
如何快速使用Langchain上手编程
python·langchain
问心无愧051327 分钟前
ctf show web 入门152
前端·笔记
kyriewen27 分钟前
Copilot下个月按Token收钱,我算了一笔账:重度用户一年要多花3000块
前端·javascript·openai
念恒1230631 分钟前
Python(for循环进阶)
开发语言·python
AI玫瑰助手41 分钟前
Python运算符:算术运算符(加减乘除取模幂)详解
开发语言·python
情绪总是阴雨天~1 小时前
深度解析:LangChain、Agent、RAG、FC、ReAct、LangGraph、A2A、MCP — 区别、联系与全景图
python·langchain·agent·rag·langgraph·mcp·a2a
还有多久拿退休金1 小时前
dnd-kit 碰撞检测算法:你的订单为什么自己"跑"到了 1 号?
前端
qq_316837751 小时前
npm run tauri build Downloading下载超时
前端·npm·node.js