面向新手解析python Beautiful Soup基本用法
作者:夏日的向日葵 发布时间:2023-11-06 22:29:50
Beautiful Soup就是Python的一个HTML或XML的解析库,可以用它来方便地从网页中提取数据。它有如下三个特点:
Beautiful Soup提供一些简单的、Python式的函数来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。
Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为UTF-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时你仅仅需要说明一下原始编码方式就可以了。
Beautiful Soup已成为和lxml、html6lib一样出色的Python解释器,为用户灵活地提供不同的解析策略或强劲的速度。
首先,我们要安装它:pip install bs4,然后安装 pip install beautifulsoup4.
Beautiful Soup支持的解析器
下面我们以lxml解析器为例:
from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>Hello</p>', 'lxml')
print(soup.p.string)
结果:
Hello
beautiful soup美化的效果实例:
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" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')#调用prettify()方法。这个方法可以把要解析的字符串以标准的缩进格式输出
print(soup.prettify())
print(soup.title.string)
结果:
<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" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">
<!-- Elsie -->
</a>
,
<a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">
Lacie
</a>
and
<a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">
Tillie
</a>
;
and they lived at the bottom of a well.
</p>
<p class="story">
...
</p>
</body>
</html>
The Dormouse's story
下面举例说明选择元素、属性、名称的方法
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" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print('输出结果为title节点加里面的文字内容:\n',soup.title)
print('输出它的类型:\n',type(soup.title))
print('输出节点的文本内容:\n',soup.title.string)
print('结果是节点加其内部的所有内容:\n',soup.head)
print('结果是第一个p节点的内容:\n',soup.p)
print('利用name属性获取节点的名称:\n',soup.title.name)
#这里需要注意的是,有的返回结果是字符串,有的返回结果是字符串组成的列表。
# 比如,name属性的值是唯一的,返回的结果就是单个字符串。
# 而对于class,一个节点元素可能有多个class,所以返回的是列表。
print('每个节点可能有多个属性,比如id和class等:\n',soup.p.attrs)
print('选择这个节点元素后,可以调用attrs获取所有属性:\n',soup.p.attrs['name'])
print('获取p标签的name属性值:\n',soup.p['name'])
print('获取p标签的class属性值:\n',soup.p['class'])
print('获取第一个p节点的文本:\n',soup.p.string)
结果:
输出结果为title节点加里面的文字内容:
<title>The Dormouse's story</title>
输出它的类型:
<class 'bs4.element.Tag'>
输出节点的文本内容:
The Dormouse's story
结果是节点加其内部的所有内容:
<head><title>The Dormouse's story</title></head>
结果是第一个p节点的内容:
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
利用name属性获取节点的名称:
title
每个节点可能有多个属性,比如id和class等:
{'class': ['title'], 'name': 'dromouse'}
选择这个节点元素后,可以调用attrs获取所有属性:
dromouse
获取p标签的name属性值:
dromouse
获取p标签的class属性值:
['title']
获取第一个p节点的文本:
The Dormouse's story
在上面的例子中,我们知道每一个返回结果都是bs4.element.Tag类型,它同样可以继续调用节点进行下一步的选择。
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print('获取了head节点元素,继续调用head来选取其内部的head节点元素:\n',soup.head.title)
print('继续调用输出类型:\n',type(soup.head.title))
print('继续调用输出内容:\n',soup.head.title.string)
结果:
获取了head节点元素,继续调用head来选取其内部的head节点元素:
<title>The Dormouse's story</title>
继续调用输出类型:
<class 'bs4.element.Tag'>
继续调用输出内容:
The Dormouse's story
(1)find_all()
find_all,顾名思义,就是查询所有符合条件的元素。给它传入一些属性或文本,就可以得到符合条件的元素,它的功能十分强大。
find_all(name , attrs , recursive , text , **kwargs)
他的用法:
html='''
<div class="panel">
<div class="panel-heading">
<h4>Hello</h4>
</div>
<div class="panel-body">
<ul class="list" id="list-1">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>
<ul class="list list-small" id="list-2">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>
</div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print('查询所有ul节点,返回结果是列表类型,长度为2:\n',soup.find_all(name='ul'))
print('每个元素依然都是bs4.element.Tag类型:\n',type(soup.find_all(name='ul')[0]))
#将以上步骤换一种方式,遍历出来
for ul in soup.find_all(name='ul'):
print('输出每个u1:',ul.find_all(name='li'))
#遍历两层
for ul in soup.find_all(name='ul'):
print('输出每个u1:',ul.find_all(name='li'))
for li in ul.find_all(name='li'):
print('输出每个元素:',li.string)
结果:
查询所有ul节点,返回结果是列表类型,长度为2:
[<ul class="list" id="list-1">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>, <ul class="list list-small" id="list-2">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>]
每个元素依然都是bs4.element.Tag类型:
<class 'bs4.element.Tag'>
输出每个u1: [<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>]
输出每个u1: [<li class="element">Foo</li>, <li class="element">Bar</li>]
输出每个u1: [<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>]
输出每个元素: Foo
输出每个元素: Bar
输出每个元素: Jay
输出每个u1: [<li class="element">Foo</li>, <li class="element">Bar</li>]
输出每个元素: Foo
输出每个元素: Bar
来源:https://www.cnblogs.com/xiao02fang/p/13269984.html
猜你喜欢
- 打算学习linux和考一下认证。学习HCIA-AI实验手册发现的小问题和记录贴,防止自己忘。我不知道这个手册是不是公开的,你们自己去华为下载
- 在读取文件时将整数变量读成了字符串, 或者需要转换列属性时,通过方法astypePython中举例:dataframe.numbers=da
- python条件语句使用 if 表达式,难度不高,需要注意的是嵌套用法,以及如何设置对应的条件。if 条件判断语句python 语句是按固定
- ASP(Active Server Page)是Microsoft公司推出的基于PWS(Personal We
- PyAutoGUI是一个Python语言的键鼠自动化库,简单来说和按键精灵的功能一样。但是因为是Python的类库,所以可以使用Python
- 概述线性回归 (Linear Regression) 是利用回归分析来确定两种或两种以上变量间相互依赖的定量关系.对线性回归还不是很了解的同
- 1. 准备工作有朋友可能没用过folium,它其实就是python的一个专业绘制地图的第三方库,所以在使用之前需要先安装它。pip 
- 大家都用过企业管理器中的--“收缩数据库”,里面的功能的确可以收缩数据库的日志文件(.ldf)和数据文件(.mdf),但都会发现同样的问题,
- 打开一个Project在导航区带出多个Project将会影响PyCharm的运行速度,解决这个问题的方式只打开一个即可。有时候打开一个Pro
- python常见的错误有1.NameError变量名错误2.IndentationError代码缩进错误3.AttributeError对象
- 1.怎么样查看数据库字符集 [A]数据库服务器字符集select * from nls_database_parameters,其来源于pr
- 我们都知道python的版本不同,在使用的时候就有所区别。鉴于我们推荐小伙伴们选择python3版本,所以这方面的区别了解的不是很多。就拿_
- 前言本文紧接着前一篇的入门教程,会介绍一些关于pandas的进阶知识。建议读者在阅读本文之前先看完pandas入门教程。同样的,本文的测试数
- 介绍Matplotlib是Python中使用最广泛的数据可视化库之一。Matplotlib的受欢迎程度大部分来自其自定义选项。您可以调整其对
- 彩色螺旋线的绘制代码如下:import turtleimport timeturtle.pensize(2)turtle.bgcolor(&
- 代码如下webfig1.pyfrom flask import Flaskfrom flask import render_template
- 本文实例为大家分享了python实现矩阵打印的具体代码,供大家参考,具体内容如下之前面试嵌入式软件的一道题,用c实现矩阵打印,考场上并没有写
- pytest fixtures装饰器pytest中可以使用@pytest.fixture 装饰器来装饰一个方法,被装饰方法的方法名可以作为一
- 本文实例讲述了php中对象引用和复制。分享给大家供大家参考,具体如下:引用$tv2 = $tv1;或者$tv2 = &$tv1;以上
- 看新闻说Chrome的Javascript引擎很强大,执行速度很快。就随便写了一个1,000,000次的累加放到IE和Chrome下测试,效