面向新手解析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


猜你喜欢
- <html><head><title>不刷新页面查询的方法</title><meta
- 前言将Selenium程序编写为 .bat 可执行文件,从此一键启动封装好的Selenium程序,省时省力还可以复用,岂不美哉应用场景写好
- Python内置模块logging管理不同级别log打印和存储,非常方便,从此告别了使用print打桩记录,我们来看下logging的魅力吧
- 本文实例讲述了php简单生成随机字符串的方法。分享给大家供大家参考,具体如下:生成一组:<?php$str = "01234
- <html>位于网页的顶端它没有父辈,称之为根节点1.元素节点(element node)可以说,整个DOM模型都是由元素节点(
- 本文介绍一个用python结合xlsxwriter自动生成业务报表的程序。这里的业务数据采用的是指定的值,真实情况下需要其他程序来接入数据。
- SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在
- 问题一开始安装的Autoprefixer是最新版本的3.0.1,一波操作后发现无效想是不是因为没设置browsers?那就设置一下吧&quo
- 1. 解压ZIP包和配置首先,将mysql-5.5.25-winx64.zip 解压缩到D:/mysql-5.5.25 目录下,然后根据网上
- 引言软件开发经历了许多阶段,如需求收集和分析、设计、软件开发、测试和发布。测试是 SDLC 不可或缺的一部分,单元测试是一种可靠的测试类型。
- 已解决卸载pip重新安装的方法问题需求粉丝群里面的一个小伙伴遇到问题跑来私信我,想用卸载pip重新安装pip,但是发生了报错(当时他心里瞬间
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN&
- 前言如果想分布式执行用例,用例设计必须遵循以下原则:1、用例之间都是独立的,2、用例a不要去依赖用例b3、用例执行没先后顺序,4、随机都能执
- 1 引言这段时间在研究美团爬虫,用的是scrapy-redis分布式爬虫框架,奈何scrapy-redis与scrapy框架不同,默认只发送
- 如何分析程序运行所需时间及cpu的使用率?使用shell内置的time指令最常见的方式便是linux中内置的time指令,通过time go
- 1. 前言vue-cli 一个简单的构建Vue.js项目的命令行界面整体过程:$ npm install -g vue-cli $ vue
- 有时候有很多逗号,这样我们就不好处理了,下面的函数就是将多个逗号替换为一个逗号,方便后面的处理。<script language=&q
- 我就废话不多说了,直接上代码吧!#全0和全1矩阵v1 = tf.Variable(tf.zeros([3,3,3]), name="
- 本文实例讲述了Golang算法之田忌赛马问题实现方法。分享给大家供大家参考,具体如下:【田忌赛马问题】输入:输入有多组测试数据。 每组测试数
- 一、BeautifulSoup4 基础知识补充BeautifulSoup4 是一款 python 解析库,主要用于解析 HTML