python3解析库BeautifulSoup4的安装配置与基本用法

yizhihongxing

Python3解析库BeautifulSoup4的安装配置与基本用法

什么是BeautifulSoup4

BeautifulSoup4 是一个 HTML 或 XML 的解析库,可以将复杂的 HTML 或 XML 文档转换成一个树形结构,提供简单的、Python 风格的 API 来遍历文档。它可以解析 HTML 和 XML 标记文档,支持 HTML5 标准,同时还支持在其中查找标记、修改标签属性和添加新标记等操作,是爬虫中常用的一个库。

安装BeautifulSoup4

使用 pip 命令来安装 BeautifulSoup4,打开命令行,输入以下命令:

pip install beautifulsoup4

如果出现权限问题,使用管理员权限运行命令行窗口。

基本使用

首先导入 Beautiful Soup 库:

from bs4 import BeautifulSoup

解析静态 HTML 页面

使用 BeautifulSoup 类的 soup = BeautifulSoup(html_doc, 'html.parser') 方法解析静态 HTML 页面,其中 html_doc 是要解析的 HTML 页面。

例如:

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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>
"""

soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())

运行结果:

<html>
 <head>
  <title>
   The Dormouse's story
  </title>
 </head>
 <body>
  <p class="title">
   <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>

使用 prettify() 方法可以打印出解析后的 HTML 页面的结构,更加清晰明了。

解析动态 HTML 页面

解析动态 HTML 页面需要使用 Python 的 Requests 库等第三方库来获取 HTML 代码。例如:

import requests
from bs4 import BeautifulSoup

url = 'https://www.zhihu.com/explore'

r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
print(soup.prettify())

运行结果:

<!DOCTYPE doctype html>
<html data-theme="light" lang="zh">
 <head>
  <title>
   发现 - 知乎
  </title>
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"/>
  <meta content="default" name="apple-mobile-web-app-status-bar-style"/>
  <meta charset="utf-8"/>
  <meta content="yes" name="apple-mobile-web-app-capable"/>
...

可以看到,这样就可以获取到动态 HTML 页面的代码,然后通过 BeautifulSoup 进行解析。

BeautifulSoup4 常用方法

find 和 find_all

find() 方法可以搜索文档树,查找符合条件的第一个元素,例如:

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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>
"""

soup = BeautifulSoup(html_doc, 'html.parser')
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>]

find_all() 方法可以查找文档中所有符合条件的元素,例如:

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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>
"""

soup = BeautifulSoup(html_doc, 'html.parser')
for link in soup.find_all('a'):
    print(link.get('href'))

运行结果:

http://example.com/elsie
http://example.com/lacie
http://example.com/tillie

select

select() 方法可以支持一些 CSS 选择器的功能,例如:

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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>
"""

soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.select('title'))

运行结果:

[<title>The Dormouse's story</title>]

获取标签属性

使用标签对象的 tag['attribute'] 可以获取标签属性的值,例如:

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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>
"""

soup = BeautifulSoup(html_doc, 'html.parser')
tag = soup.a
print(tag['href'])

运行结果:

http://example.com/elsie

修改标签属性和字符串

例如:

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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>
"""

soup = BeautifulSoup(html_doc, 'html.parser')
soup.a['href'] = 'http://new-link.com'
soup.a.string = 'New Link'
print(soup.prettify())

运行结果:

<html>
 <head>
  <title>
   The Dormouse's story
  </title>
 </head>
 <body>
  <p class="title">
   <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://new-link.com" id="link1">
    New Link
   </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>

以上就是 BeautifulSoup4 库的安装配置及基本用法的详细攻略。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python3解析库BeautifulSoup4的安装配置与基本用法 - Python技术站

(0)
上一篇 2023年6月10日
下一篇 2023年6月10日

相关文章

  • 谨慎使用CSS中的星号(*)通配符

    谨慎使用CSS中的星号(*)通配符 CSS中的星号()通配符可以匹配任何元素,它可以用来设置全局样式或者重置默认样式。然而,过度使用星号通配符会导致性能问题和样式冲突。本攻略将详细讲解如何谨慎使用CSS中的星号()通配符,包括使用场景、注意事项和示例说明。 1. 使用场景 星号(*)通配符可以用于以下场景: 重置默认样式:使用星号通配符可以重置所有元素的默认…

    css 2023年5月18日
    00
  • 表格里使用text-overflow后不能隐藏超出的文本的解决方法

    表格中使用 text-overflow 属性可以限制表格单元格中文本的显示。当单元格中文本过多时,可以使用 text-overflow: ellipsis 属性让文本在末尾显示省略号,从而提供更好的用户体验。 然而,某些情况下,text-overflow 属性可能无法成功隐藏超出的文本。这种情况通常出现在单元格中存在其他属性(如 white-space)时,…

    css 2023年6月10日
    00
  • 兼容主流浏览器的jQuery+CSS 实现遮罩层的简单代码

    接下来是详细讲解“兼容主流浏览器的jQuery+CSS 实现遮罩层的简单代码”的完整攻略。 首先,需要说明一下遮罩层的概念。遮罩层是一种常见的页面蒙版(或称为遮挡层),一般情况下用于模拟弹窗、广告等强制性消息窗口。我们需要在页面上添加一个遮罩层,通过覆盖整个网页并给予透明度,使得用户无法操作网页内的元素,同时突出弹出的窗口。 接下来,我们来分步骤讲解 jQu…

    css 2023年6月10日
    00
  • 值得收藏的CSS命名规范(规则)常用的CSS命名规则

    下面是关于“值得收藏的CSS命名规范(规则)常用的CSS命名规则”的详细讲解,包含以下内容: 什么是CSS命名规范? CSS命名规范是指在编写CSS代码时,根据一定的规则和标准对CSS样式名称进行命名的方式。通过遵循CSS命名规范,我们可以更好地组织和管理我们的代码,从而提高代码的可读性和可维护性。 常用的CSS命名规则 1. BEM命名法 BEM是一种广泛…

    css 2023年6月9日
    00
  • 修改CSS样式实现网页灰色(没有颜色只有浅色黑白)的几个方法整理

    下面我将详细讲解“修改CSS样式实现网页灰色(没有颜色只有浅色黑白)的几个方法整理”的完整攻略。 一、概述 将网页修改为灰色,也被称为“去色”或“黑白化”网页,这种效果通常被用于强调页面内容,从而提高信息传达效果和阅读体验。本攻略将针对实现网页灰色的几种方法做出详细的说明,并提供相关示例。 二、方法详解 1. 使用CSS3的filter CSS3中提供了一种…

    css 2023年6月9日
    00
  • 深入解析CSS的display:inline-block属性的使用

    深入解析CSS的display:inline-block属性的使用 什么是display:inline-block? display:inline-block 是 CSS 属性中的一种取值,可以将元素设为行内级盒模型,并且可以设置 width、height、margin 和 padding 等属性。同时,该元素在水平方向上是相邻排列,垂直方向上的距离和行内元…

    css 2023年6月10日
    00
  • vue2.0 和 animate.css的结合使用

    那么现在我来为您讲解一下“Vue2.0 和 Animate.css 的结合使用”的完整攻略。 什么是 Vue2.0 和 Animate.css Vue 是一个渐进式 JavaScript 框架,用于构建用户界面。它具有响应式系统、组件化机制、指令等特点,可以轻松的管理数据和 DOM。 Animate.css 是一个跨浏览器的 CSS 库,包含了各种 CSS …

    css 2023年6月10日
    00
  • CSS3实现翘边的阴影效果的代码示例

    CSS3可以通过box-shadow属性实现翘边的阴影效果,具体的代码实现过程如下: 1.先定义一个带有背景色的div元素: <div style="background-color: #ccc; width: 200px; height: 100px;"></div> 2.在此div元素上添加CSS样式,实现翘边…

    css 2023年6月10日
    00
合作推广
合作推广
分享本页
返回顶部