Python从0到100(三十五):beautifulsoup的学习

news/2024/7/23 20:29:49 标签: python, beautifulsoup, 学习

在这里插入图片描述

前言: 零基础学Python:Python从0到100最新最全教程。 想做这件事情很久了,这次我更新了自己所写过的所有博客,汇集成了Python从0到100,共一百节课,帮助大家一个月时间里从零基础到学习Python基础语法、Python爬虫、Web开发、 计算机视觉、机器学习、神经网络以及人工智能相关知识,成为学习学习和学业的先行者!
欢迎大家订阅专栏:零基础学Python:Python从0到100最新最全教程!

1 BeautifulSoup4的介绍和安装

和 lxml 一样,Beautiful Soup 也是一个HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 数据。

lxml 只会局部遍历,而Beautiful Soup 是基于HTML DOM的,会载入整个文档,解析整个DOM树,因此时间和内存开销都会大很多,所以性能要低于lxml。

BeautifulSoup 用来解析 HTML 比较简单,API非常人性化,支持CSS选择器、Python标准库中的HTML解析器,也支持 lxml 的 XML解析器。

Beautiful Soup 3 目前已经停止开发,推荐现在的项目使用Beautiful Soup 4。使用 pip 安装即可:
pip install beautifulsoup4

1.1 bs4的基本使用示例:

首先必须要导入 bs4 库

python">from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""

#创建 Beautiful Soup 对象
soup = BeautifulSoup(html)
# soup = BeautifulSoup(html, 'lxml')

#打开本地 HTML 文件的方式来创建对象
#soup = BeautifulSoup(open('index.html'))

#格式化输出 soup 对象的内容
print(soup.prettify())

运行结果:

<html>
 <head>
  <title>
   The Dormouse's story
  </title>
 </head>
 <body>
  <p class="title" name="dromouse">
   <b>
    The Dormouse's story
   </b>
  </p>
  <p class="story">
   Once upon a time there were three little sisters; and their names were
   <a class="sister" href="http://example.com/elsie" id="link1">
    <!-- Elsie -->
   </a>
   ,
   <a class="sister" href="http://example.com/lacie" id="link2">
    Lacie
   </a>
   and
   <a class="sister" href="http://example.com/tillie" id="link3">
    Tillie
   </a>
   ;
and they lived at the bottom of a well.
  </p>
  <p class="story">
   ...
  </p>
 </body>
</html>

2 搜索文档树

2.1 find_all(name, attrs, recursive, text, **kwargs)

1) name 参数

name 参数可以查找所有名字为 name 的tag

A 传字符串

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

python">print(soup.find_all('b'))
# [<b>The Dormouse's story</b>]

print(soup.find_all('a'))
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
B 传正则表达式

如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以b开头的标签,这表示和标签都应该被找到

python">import re
for tag in soup.find_all(re.compile("^b")):
    print(tag.name)
# body
# b
C 传列表

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

python">print(soup.find_all(["a", "b"]))
# [<b>The Dormouse's story</b>,
#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

2)keyword 参数

python">print(soup.find_all(class_="sister")) # 注意 这里是class_ 最后有个下划线!
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

print(soup.find_all(id='link2'))
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

3)text 参数

通过 text 参数可以搜索文档中的字符串内容,与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表

python">import re

print(soup.find_all(text=" Elsie ")) # 注释内容不能少了空格!
# [' Elsie ']

print(soup.find_all(text=["Tillie", "Elsie", "Lacie"])) # 这就找不到注释内容!
# ['Lacie', 'Tillie']

print(soup.find_all(text=re.compile("Dormouse")))
["The Dormouse's story", "The Dormouse's story"]

2.2 find

find的用法与find_all一样,区别在于find返回 第一个符合匹配结果,find_all则返回 所有匹配结果的列表

2.3 CSS选择器

这就是另一种与 find_all 方法有异曲同工之妙的查找方法,也是返回所有匹配结果的列表。

  • 写 CSS 时,标签名不加任何修饰,类名前加.,id名前加#

  • 在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list

(1)通过标签选择器查找

python">print(soup.select('title'))
#[<title>The Dormouse's story</title>]

print(soup.select('a'))
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

print(soup.select('b'))
#[<b>The Dormouse's story</b>]

(2)通过类选择器查找

python">print(soup.select('.sister'))
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

(3)通过 id 选择器查找

python">print(soup.select('#link1'))
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

(4)层级选择器 查找

python">print(soup.select('p #link1'))
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

(5)通过属性选择器查找

python">print(soup.select('a[class="sister"]'))
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

print(soup.select('a[href="http://example.com/elsie"]'))
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

(6) 获取文本内容 get_text()

以上的 select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text() 方法来获取它的内容。

python">soup = BeautifulSoup(html, 'lxml')
print(type(soup.select('title')))
print(soup.select('title')[0].get_text())

for title in soup.select('title'):
    print(title.get_text())

(7) 获取属性 get(‘属性的名字’)

python">soup = BeautifulSoup(html, 'lxml')
print(type(soup.select('a')))
print(soup.select('a')[0].get('href'))

http://www.niftyadmin.cn/n/5546696.html

相关文章

【分布式系统】ceph部署(命令+截图巨详细版)

目录 一.存储概述 1.单机存储设备 2.单机存储的问题 3.商业存储 4.分布式存储​编辑 4.1.什么是分布式存储 4.2.分布式存储的类型 二.ceph概述 1.ceph优点 2.ceph架构 3.ceph核心组件 4.OSD存储后端 5.ceph数据存储过程 6.ceph版本发行生命周期 7.ceph集群部署 …

【状态估计】非线性非高斯系统的状态估计——离散时间的批量估计

上一篇文章介绍了离散时间的递归估计&#xff0c;本文着重介绍离散时间的批量估计。 上一篇位置&#xff1a;【状态估计】非线性非高斯系统的状态估计——离散时间的递归估计。 离散时间的批量估计问题 最大后验估计 目标函数 利用高斯-牛顿法来解决估计问题的非线性版本&a…

c语言中运算符的优先级

在C语言中&#xff0c;运算符的优先级决定了表达式中各个部分执行的顺序。了解运算符的优先级对于编写正确和预期行为的代码非常重要。下面是一个简化的C语言运算符优先级列表&#xff0c;从高到低排列&#xff1a; 括号 ()&#xff1a;用于改变运算顺序&#xff0c;具有最高优…

C语言希尔排序详解与实例

希尔排序&#xff08;Shell Sort&#xff09;&#xff0c;是由Donald Shell在1959年提出的一种排序算法。它是插入排序的一种高效改进版&#xff0c;通过引入“增量”概念&#xff0c;将原本的线性查找转换为分段查找&#xff0c;从而显著提升了排序效率。本文将深入探讨希尔排…

windows JDK11 与JDK1.8自动切换,以及切换后失效的问题

1.windows安装不同环境的jdk 2.切换jdk 3.切换失败 原因&#xff1a;这是因为当我们安装并配置好JDK11之后它会自动生成一个环境变量&#xff08;此变量我们看不到&#xff09;&#xff0c;此环境变量优先级较高&#xff0c;导致我们在切换回JDK8后系统会先读取到JDK11生成的…

TransDecoder:转录本基因预测(真菌)

安装 Home TransDecoder/TransDecoder Wiki GitHub wget -c https://data.broadinstitute.org/Trinity/CTAT_SINGULARITY/MISC/TransDecoder/transdecoder.v5.7.1.simg mamba create -n TransDecoder mamba activate TransDecoder mamba install -c conda-forge singulari…

【Python】已解决:SyntaxError: invalid character in identifier

文章目录 一、分析问题背景二、可能出错的原因三、错误代码示例四、正确代码示例五、注意事项 已解决&#xff1a;SyntaxError: invalid character in identifier 一、分析问题背景 在Python编程中&#xff0c;SyntaxError: invalid character in identifier是一个常见的编译…

成都百洲文化传媒有限公司电商服务的领跑者

在电商行业的风起云涌中&#xff0c;成都百洲文化传媒有限公司凭借其专业的服务能力和对市场的敏锐洞察&#xff0c;成为了众多品牌争相合作的伙伴。作为电商服务领域的佼佼者&#xff0c;百洲文化传媒凭借其独特的优势&#xff0c;帮助众多品牌实现了从线下到线上的华丽转身&a…