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())
相关推荐
jiuri_12151 小时前
Docker使用详解:在ARM64嵌入式环境部署Python应用
python·docker·容器
chenchihwen1 小时前
AI代码开发宝库系列:Function Call
人工智能·python·1024程序员节·dashscope
李少兄3 小时前
HTML 表单控件
前端·microsoft·html
汤姆yu3 小时前
基于python的化妆品销售分析系统
开发语言·python·化妆品销售分析
学习笔记1014 小时前
第十五章认识Ajax(六)
前端·javascript·ajax
消失的旧时光-19434 小时前
Flutter 异步编程:Future 与 Stream 深度解析
android·前端·flutter
上去我就QWER4 小时前
Python下常用开源库
python·1024程序员节
曹牧4 小时前
C# 中的 DateTime.Now.ToString() 方法支持多种预定义的格式字符
前端·c#
勿在浮沙筑高台4 小时前
海龟交易系统R
前端·人工智能·r语言