百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Python每日一库之Beautiful Soup(python mtime)

zhezhongyun 2025-01-29 19:11 56 浏览



Beautiful Soup4是一个 Python 库,用于从 HTML 和 XML 文件中提取数据。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。

BeautifulSoup安装

使用pip来安装BeautifulSoup

pip install bs4 

另外要安装解析器,下列表格列出一些常用的解析器。



解析器

使用方法

优点

缺点

Python内置解析器html

BeautifulSoup(doc,"html.parser")

Python内置的标准库,执行速度中等,文档容错能力强

中文文档容错能力差

lxml HTML解析器

BeautifulSoup(doc,"lxml")

执行速度快,文档容错能力强

需要依赖C语言的库


lxml XML解析器

BeautifulSoup(doc,"xml")

执行速度快,唯一支持XML的解析器

需要依赖C语言的库

html5lib

BeautifulSoup(doc,"html5lib")

以浏览器的方式解析文档可以生成HTML5格式的文档

速度慢

使用BeautifulSoup及四大对象

创建BeautifulSoup对象

from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"

content = requests.get(url).content
soup = BeautifulSoup(content)

print(soup.prettify())  // 格式化输出

print(soup.get_text()) // 获取网页所有的文字内容

BeautifulSoup四大对象

Beautiful Soup 将复杂 HTML 文档转换成一个复杂的树形结构,每个节点都是 Python 对象,所有对象可以归纳为 4 种。

  • Tag:HTML中的标签,简单来说就是html标签。
  • NavigableString:简单来说就是标签里面的内容,它的类型是一个NavigableString,翻译过来叫可以遍历的字符串。
  • BeautifulSoup:BeautifulSoup对象表示的是一个文档的全部内容,大部分时候,可以把它当作Tag对象,是一个特殊的Tag,我们可以分别获取它的类型、名称、以及属性
  • Comment:一个特殊类型的NavigableString对象,其实输出的内容不包括注释符号

Tag对象示例

from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"

content = requests.get(url).content
soup = BeautifulSoup(content)

print(soup.title)
print(soup.a)
print(soup.p)

运行输出如下图所示,但是发现好像这个网页不止一个a标签跟p标签,是因为它查找的是在所有内容中的第一个符合要求的标签,要是想得到所有符合要求的标签,后面会介绍find_all函数。

在Tag对象中有两个重要的属性,name和attrs。

from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content)
print(soup.a.attrs)

运行输出如下图所示,name输出的是标签的本身,attrs输出的是一个字典的类型,如果我们需要得到某个标签的某个属性可以使用字典一些方法去获取比如get方法,print(soup.p.get("class"))或者直接使用print(soup.p["class"])

NavigableString代码示例

from bs4 import BeautifulSoup
import requests
url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content)
print(soup.a.string)

运行输出如下图,可以NavigableString类型的string方法轻松获取到了标签里面的内容。

BeautifulSoup代码示例

from bs4 import BeautifulSoup
import requests
url = "https://www.baidu.com"

content = requests.get(url).content
soup = BeautifulSoup(content)
print(soup.name)
print(soup.attrs)

运行输出如下图所示

Comment代码示例

from bs4 import BeautifulSoup
htmlText = '#'
soup = BeautifulSoup(htmlText)
print(soup.a.string)

运行输出如下,a 标签里的内容实际上是注释,但是如果利用 .string方法来输出它的内容,发现它已经把注释符号去掉了,所以这可能会给带来不必要的麻烦。

文档树遍历

  • 直接子节点

tag里面的content属性可以将tag的子节点以列表的形式返回。通过遍历content.返回的列表来获取每一个子节点或者直接使用tag的children方法来获取。

from bs4 import BeautifulSoup
import requests
url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content)
print(soup.head.contents)
for child in soup.head.contents:
    print(child)

for child in soup.head.children:
    print(child)

运行输出结果如下图所示

  • 所有子孙节点

tag里面的.descendants 属性可以对所有tag的子孙节点进行递归循环,和 children类似,我们也需要遍历获取其中的内容。

from bs4 import BeautifulSoup
import requests
url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content)
for child in soup.descendants:
     print(child)

运行结果输出如下图所示

  • 节点内容

使用.string方法来获取内容,如果一个标签里面没有标签了,那么 .string 就会返回标签里面的内容。如果标签里面只有唯一的一个标签了,那么 .string 也会返回最里面的内容,如果标签里面没有内容则返回None

from bs4 import BeautifulSoup
import requests
url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content)
print(soup.a.string)
print(soup.title.string)

运行结果输出如下图所示

  • 多个内容

使用strippend_strings 属性来获取多个内容还可以出除多余的空白字符,需要使用遍历来获取,

from bs4 import BeautifulSoup
import requests
url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content)
for child in soup.stripped_strings:
    print(child)

运行结果输出如下图所示

  • 父节点

通过元素的 .parents 属性可以递归得到元素的所有父辈节点

from bs4 import BeautifulSoup
import requests
url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"html.parser")
parentObject = soup.head.title

for parent in parentObject.parent:
    print(parent.name)

运行结果输出如下图所示

还有一些节点就不举例,跟其它获取节点一样也是需要遍历,而且使用的场景不同,兄弟节点使用.next_siblings或者.previous_sibling方法,前后节点使用.next_element或者.previous_element方法。

搜索文档树

find_all(name,attrs,recursive,text,**kwargs),find_all()方法用于搜索当前tag的所有tag子节点,并判断是否符合过滤条件。

name 参数

name参数可以查找所有名字为name的tag,字符串对象会被自动忽略掉

  • 传字符串

最简单的过滤器是字符串,在搜索方法中传入一个字符串参数,beautifulsoup会查找与字符串完整匹配的内容,下面的例子用于查找文档中的所有a标签

from bs4 import BeautifulSoup
import requests
url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")

print(soup.find_all("a"))
  • 传正则表达式

如果传入正则表达式作为参数,beautiful soup会通过正则表达式的match()来匹配内容,下面例子中找出所有以b开头的标签,这表示b开头标签都应该被找到,如果都正则表达式不熟悉的可以看我之前写关于正则表示式的文章:
https://www.toutiao.com/article/7140941215431819783/?log_from=
4bb8705803d45_1663051238064

from bs4 import BeautifulSoup
import requests
import re
url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")

for tag in soup.find_all(re.compile('^b')):
    print(tag.name)

运行结果如下图所示

  • 传列表

如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有标签和标签

from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")

print(soup.find_all(["a", "p"]))

运行结果如下图所示

  • 传True

true 可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点

from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")

for tag in soup.find_all(True):
    print(tag.name)

运行结果如下图所示

  • 传函数

如果没有合适过滤器,那么还可以定义一个函数,函数只接受一个元素参数 [4] ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则返回 False

from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")


def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')

print(soup.find_all(has_class_but_no_id))

输出结果如下图所示

  • keyword 参数

注意:如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为id的参数,Beautifulsoup会搜索每个tag的'id'值

import re

from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")
print(soup.find_all(id='lg'))
print(soup.find_all(href=re.compile("hao123")))

运行结果如下图所示

  1. find(name , attrs , recursive , text , **kwargs ), 它与 find_all() 方法唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果。

CSS选择器

在使用BeautifulSoup中常用的有5中css选择器方法,用到的方法是 soup.select(),返回类型是列表

  • 通过标签名查找
from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")
print(soup.select("title"))

运行结果如下图所示

  • 通过CSS类名查找
from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")
print(soup.select(".mnav"))

运行结果如下图所示

  • 通过ID来查找
from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")
print(soup.select("#lg"))

运行结果如下图所示

  • 组合查找

组合查找有点类似前端CSS选择器中的组合选择器,组合查找还可以使用子代选择器。

from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")
print(soup.select('div #lg'))

print(soup.select('div > a'))

运行结果如下图所示

  • 通过CSS属性查找

使用属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。

from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")
print(soup.select('a[class="mnav"]'))

不同节点使用属性查找

from bs4 import BeautifulSoup
import requests

url = "https://www.baidu.com"
content = requests.get(url).content
soup = BeautifulSoup(content,"lxml")
print(soup.select('span input[class="bg s_btn"]'))

运行结果如下图所示


修改文档树

Beautiful Soup的强项是文档树的搜索,但同时也可以方便的修改文档树

  • 修改tag的名称和属性
from bs4 import BeautifulSoup
import requests

soup = BeautifulSoup('Extremely bold',"lxml")

tag = soup.b

tag.name = "newtag"
tag['class'] = 'newclass'
tag['id'] = 1
print(tag)

del tag['class']
print(tag)

运行结果如下图所示

  • 修改标签内容

给tag的 .string 属性赋值,就相当于用当前的内容替代了原来的内容,如果当前的tag包含了其它tag,那么给它的 .string 属性赋值会覆盖掉原有的所有内容包括子tag

from bs4 import BeautifulSoup
import requests

markup = 'I linked to example.com'
soup = BeautifulSoup(markup,"lxml")

tag = soup.a
tag.string = "New link text."
print(tag)

运行结果如下图所示

  • 在tag中添加内容

Tag.append() 方法可以在tag中添加内容

from bs4 import BeautifulSoup
import requests

soup = BeautifulSoup("Foo","lxml")
soup.a.append("Bar")
print(soup)
print(soup.a.contents)

运行结果如下图所示

总结

本篇内容比较多,把 Beautiful Soup 的方法进行了大部分整理和总结,但是还不够完整只是列出一些常用的,如果需要完整的可以查看Beautiful Soup 官网的文档,希望对大家有帮助,掌握了 Beautiful Soup,一定会给你在数据爬取带来方便,下一期我将分享Python pands库,果对我的文章感兴趣可以关注我,如果有想了解的Python库也可以在评论留言,我将采纳你们的意见写一篇文章来分享给大家。

相关推荐

JPA实体类注解,看这篇就全会了

基本注解@Entity标注于实体类声明语句之前,指出该Java类为实体类,将映射到指定的数据库表。name(可选):实体名称。缺省为实体类的非限定名称。该名称用于引用查询中的实体。不与@Tab...

Dify教程02 - Dify+Deepseek零代码赋能,普通人也能开发AI应用

开始今天的教程之前,先解决昨天遇到的一个问题,docker安装Dify的时候有个报错,进入Dify面板的时候会出现“InternalServerError”的提示,log日志报错:S3_USE_A...

用离散标记重塑人体姿态:VQ-VAE实现关键点组合关系编码

在人体姿态估计领域,传统方法通常将关键点作为基本处理单元,这些关键点在人体骨架结构上代表关节位置(如肘部、膝盖和头部)的空间坐标。现有模型对这些关键点的预测主要采用两种范式:直接通过坐标回归或间接通过...

B 客户端流RPC (clientstream Client Stream)

客户端编写一系列消息并将其发送到服务器,同样使用提供的流。一旦客户端写完消息,它就等待服务器读取消息并返回响应gRPC再次保证了单个RPC调用中的消息排序在客户端流RPC模式中,客户端会发送多个请...

我的模型我做主02——训练自己的大模型:简易入门指南

模型训练往往需要较高的配置,为了满足友友们的好奇心,这里我们不要内存,不要gpu,用最简单的方式,让大家感受一下什么是模型训练。基于你的硬件配置,我们可以设计一个完全在CPU上运行的简易模型训练方案。...

开源项目MessageNest打造个性化消息推送平台多种通知方式

今天介绍一个开源项目,MessageNest-可以打造个性化消息推送平台,整合邮件、钉钉、企业微信等多种通知方式。定制你的消息,让通知方式更灵活多样。开源地址:https://github.c...

使用投机规则API加快页面加载速度

当今的网络用户要求快速导航,从一个页面移动到另一个页面时应尽量减少延迟。投机规则应用程序接口(SpeculationRulesAPI)的出现改变了网络应用程序接口(WebAPI)领域的游戏规则。...

JSONP安全攻防技术

关于JSONPJSONP全称是JSONwithPadding,是基于JSON格式的为解决跨域请求资源而产生的解决方案。它的基本原理是利用HTML的元素标签,远程调用JSON文件来实现数据传递。如果...

大数据Doris(六):编译 Doris遇到的问题

编译Doris遇到的问题一、js_generator.cc:(.text+0xfc3c):undefinedreferenceto`well_known_types_js’查找Doris...

网页内嵌PDF获取的办法

最近女王大人为了通过某认证考试,交了2000RMB,官方居然没有给线下教材资料,直接给的是在线教材,教材是PDF的但是是内嵌在网页内,可惜却没有给具体的PDF地址,无法下载,看到女王大人一点点的截图保...

印度女孩被邻居家客人性骚扰,父亲上门警告,反被围殴致死

微信的规则进行了调整希望大家看完故事多点“在看”,喜欢的话也点个分享和赞这样事儿君的推送才能继续出现在你的订阅列表里才能继续跟大家分享每个开怀大笑或拍案惊奇的好故事啦~话说只要稍微关注新闻的人,应该...

下周重要财经数据日程一览 (1229-0103)

下周焦点全球制造业PMI美国消费者信心指数美国首申失业救济人数值得注意的是,下周一希腊还将举行第三轮总统选举需要谷歌日历同步及部分智能手机(安卓,iPhone)同步日历功能的朋友请点击此链接,数据公布...

PyTorch 深度学习实战(38):注意力机制全面解析

在上一篇文章中,我们探讨了分布式训练实战。本文将深入解析注意力机制的完整发展历程,从最初的Seq2Seq模型到革命性的Transformer架构。我们将使用PyTorch实现2个关键阶段的注意力机制变...

聊聊Spring AI的EmbeddingModel

序本文主要研究一下SpringAI的EmbeddingModelEmbeddingModelspring-ai-core/src/main/java/org/springframework/ai/e...

前端分享-少年了解过iframe么

iframe就像是HTML的「内嵌画布」,允许在页面中加载独立网页,如同在画布上叠加另一幅动态画卷。核心特性包括:独立上下文:每个iframe都拥有独立的DOM/CSS/JS环境(类似浏...