BuautifulSoup4库详解
1、BeautifulSoup4库简介
What is beautifulsoup ?
![]()
答:一个可以用来从HTML 和 XML中提取数据的网页解析库,支持多种解析器(代替正则的复杂用法)
2、安装
pip3 install beautifulsoup4
3、用法详解
(1)、解析器性能分析(第一个参数markup-要解析的目标代码,第二个参数为解析器)

(2)、使用方法(独孤九剑)
1、总诀式:
#author: "xian"
#date: 2018/5/7
#以下为爱丽丝梦游仙境的部分代码
html = """
<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>
"""
#小试牛刀
from bs4 import BeautifulSoup #从bs4库导入BeautifulSoup类 soup = BeautifulSoup(html,'lxml') #构造名为soup的对象
print(soup.prettify()) #prettify修饰()方法:格式化代码也就是让各位小伙伴释放眼睛压力哈哈!
print(soup.a) #选中a标签
print(soup.a['class'])#打印a标签名为class的属性值
print(soup.a.name) #打印a 标签的名字 soup.a.parent.name 找到a标签的老子
print(soup.a.string) #小伙伴们猜猜看这是干什么? 答:打印a标签的文本
print(soup.find_all('a')) #找到所有的a标签
print(soup.find(id="link3"))#找到id属性值为link3的标签 #找链接
for link in soup.find_all('a'):
print(link.get('href')) #遍历所有名为a的标签并得到其链接
#找文本
print(soup.a.get_text()) #获取a标签的文本当然小伙伴们可以任意指定想要的内容 #上面的输出
'''<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>
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
['sister']
a
Elsie
[<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>]
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
http://example.com/elsie
http://example.com/lacie
http://example.com/tillie'''
其他的小伙伴们可以根据需要获取想要的内容,掌握方法即可,具体可参见官网:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/
2、破剑式
#author: "xian"
#date: 2018/5/7
html = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<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">
<span>Elsie</span>
</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>
"""
#子节点及子孙节点(老子节点与祖宗节点的选择)的选择
from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml')
print(soup.p.contents) #contents方法将得到的结果以列表形式输出
print(soup.p.children) #是一个迭代器对象,需要用for循环才能得到器内容 children 只后期子节点
for i,child in enumerate(soup.p.children): #enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
print(i,child) #接受index 和内特
print(soup.p.descendants) #descendants 获取所有的儿子和孙子后代节点
for i,child in enumerate(soup.p.descendants):
print(i,child) #上面的输出结果
'''['\n Once upon a time there were three little sisters; and their names were\n ', < a
class ="sister" href="http://example.com/elsie" id="link1" >
< span > Elsie < / span >
< / a >, '\n', < a class ="sister" href="http://example.com/lacie" id="link2" > Lacie < / a >, '\n and\n ', < a class ="sister" href="http://example.com/tillie" id="link3" > Tillie < / a >, '\n and they lived at the bottom of a well\n ']
< list_iterator object at 0x00000156B2E76EF0 >
0
Once upon a time there were three little sisters; and their names were 1 < a class ="sister" href="http://example.com/elsie" id="link1" >
< span > Elsie < / span >
< / a >
2 3 < a class ="sister" href="http://example.com/lacie" id="link2" > Lacie < / a >
4
and 5 < a class ="sister" href="http://example.com/tillie" id="link3" > Tillie < / a >
6
and they lived at the bottom of a well < generator object descendants at 0x00000156B08910F8 >
0 Once upon a time there were three little sisters; and their names were 1 < a class ="sister" href="http://example.com/elsie" id="link1" >
< span > Elsie < / span >
< /a >
2 3 < span > Elsie < / span >
4 Elsie
5 6 7 < a class ="sister" href="http://example.com/lacie" id="link2" > Lacie < / a >
8 Lacie
9
and 10 < a class ="sister" href="http://example.com/tillie" id="link3" > Tillie < / a >
11 Tillie
12
and they lived at the bottom of a well''' #老子节点和祖宗节点方法介绍 children -- parent / descendants -- parents 小伙伴们模仿上面的可是动手试试
#兄弟节点的获取 方法为:next_siblings:获取当前对象后面的兄弟节点 previous_siblings:获取当前对象前面的兄弟节点,小伙伴们可以试试
3、破刀式
#author: "xian"
#date: 2018/5/7
#搜索文档内容 find_all() 和find()
html = """
<html><head><title>The Dormouse's story</title></head> <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>
"""
from bs4 import BeautifulSoup
import re soup = BeautifulSoup(html,'lxml')
#(1)、find_all( name , attrs , recursive , text , **kwargs )
#name参数用法详解(text参数的使用同name类似如soup.find_all(text=["Tillie", "Elsie", "Lacie"])只返回内容,小伙伴们可查阅官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/)
print(soup.find_all('head')) #查找head标签
print(soup.find_all(id='link2')) #查找id='link2'的标签
print(soup.find_all(href=re.compile("(\w+)"))) #查找所有包含href属性包含字母数字的标签
print(soup.find_all(href=re.compile("(\w+)"), id='link1')) #多重过滤
#搜索指定名字的属性时可以使用的参数值包括 字符串 , 正则表达式 , 列表, True #attrs参数用法详解
print(soup.find_all(attrs={'id':'link2'})) #attrs参数以key-value形式传入值 /返回列表类型 #(2)find( name , attrs , recursive , text , **kwargs )用法同find_all 类似只不过它只返回一个值,小伙伴们可以查找官方用法 #(3)其他方法汇总:(小伙伴们了解即可具体碰到查文档)
#find_parents() 和find_parent() 返回祖宗节点 和 返回老子节点
#find_next_siblings() 和 find_next_sibling() 返回后面所有的兄弟节点 和 返回后面第一个兄弟节点
#find_previous_siblings() 和 find_previous_sibling() 返回前面所有的兄弟节点 和 返回前面第一个兄弟节点
#find_all_next() 和 find_next() 返回节点后满足条件所有的节点 和 返回第一个满足条件的节点
#find_all_previous() 和 find_previous() 返回节点前满足条件所有的节点 和 返回第一个满足条件的节点 #上面的输出结果:
'''
[<head><title>The Dormouse's story</title></head>]
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</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>]
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
<class 'bs4.element.ResultSet'>
'''
4、破枪式
#author: "xian"
#date: 2018/5/7
#CSS选择器详解(通过select()传入css选择器即可成功选择)
html = """
<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>
"""
from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml')
print(soup.select('.title')) #选择class属性为title的标签 css选择器使用请小伙伴们查看官网
#再来一例
print(soup.select('p a#link1'))# 选择p标签下的a下的id属性为link1的标签
print(soup.select('a')[1]) #做一个切片拿到第二个a标签
#获取内容
print(soup.select('a')[1].get_text()) #上面的输出:
'''
[<p class="title"><b>The Dormouse's story</b></p>]
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
laci
33 '''
通过以上的实验,小伙伴们对bs4库是否有了一定的了解,赶紧行动起来,试试学习的效果吧!
总结:
1.建议小伙伴使用lxml解析器
2.多用find_all()和find()
3.css的select()方法掌握下
4.多练习,勤能补拙,孰能生巧,才能渐入化境!

BuautifulSoup4库详解的更多相关文章
- Lua的协程和协程库详解
我们首先介绍一下什么是协程.然后详细介绍一下coroutine库,然后介绍一下协程的简单用法,最后介绍一下协程的复杂用法. 一.协程是什么? (1)线程 首先复习一下多线程.我们都知道线程——Thre ...
- Python--urllib3库详解1
Python--urllib3库详解1 Urllib3是一个功能强大,条理清晰,用于HTTP客户端的Python库,许多Python的原生系统已经开始使用urllib3.Urllib3提供了很多pyt ...
- Struts标签库详解【3】
struts2标签库详解 要在jsp中使用Struts2的标志,先要指明标志的引入.通过jsp的代码的顶部加入以下的代码: <%@taglib prefix="s" uri= ...
- STM32固件库详解
STM32固件库详解 emouse原创文章,转载请注明出处http://www.cnblogs.com/emouse/ 应部分网友要求,最新加入固件库以及开发环境使用入门视频教程,同时提供例程模板 ...
- MySQL5.6的4个自带库详解
MySQL5.6的4个自带库详解 1.information_schema详细介绍: information_schema数据库是MySQL自带的,它提供了访问数据库元数据的方式.什么是元数据呢?元数 ...
- php中的PDO函数库详解
PHP中的PDO函数库详解 PDO是一个“数据库访问抽象层”,作用是统一各种数据库的访问接口,与mysql和mysqli的函数库相比,PDO让跨数据库的使用更具有亲和力:与ADODB和MDB2相比,P ...
- STM32 HAL库详解 及 手动移植
源: STM32 HAL库详解 及 手动移植
- 爬虫入门之urllib库详解(二)
爬虫入门之urllib库详解(二) 1 urllib模块 urllib模块是一个运用于URL的包 urllib.request用于访问和读取URLS urllib.error包括了所有urllib.r ...
- Python爬虫系列-Urllib库详解
Urllib库详解 Python内置的Http请求库: * urllib.request 请求模块 * urllib.error 异常处理模块 * urllib.parse url解析模块 * url ...
随机推荐
- 择天记OL体验截图
- java方法重写和super关键字
//java方法重写和super关键字 //在继承中,其实就是子类定义了和父类同名的方法 //就是方法,属性都是相通的 //重写限制: //被子类重写的方法不能拥有比父类方法更加严格的权限 //sup ...
- Android开发技巧——ViewPager衍生出来的2个类
1.不能左右滑动的ViewPager /* * Date: 14-7-28 * Project: Access-Control-V2 */ package cn.irains.access.v2.co ...
- Mybatis执行CachingExecutor(六)
前面几篇博客我们介绍了Excutor及抽象类BaseExecutor和实现类SimpleExecutor.BatchExecutor和ReuseExecutor: 博客列表: Mybatis执行Exe ...
- 《java入门第一季》之网络编程初探
由于在写有关javaweb的博客,在写到web服务器的时候需要回顾网络编程的知识,提前把网络编程放在前面写. 直接上代码解释: import java.net.InetAddress; import ...
- 《java入门第一季》之根据小案例体会泛型
泛型在哪些地方使用呢? * 看API,如果类,接口,抽象类后面跟的有<E>就说要使用泛型.一般来说就是在集合中使用. 下面根据案例,加深体会泛型的作用. 案例一: import java. ...
- PA模块报错-实际返回的行数超出请求的行数(分析标准FORM报错解决思路)
录入预算报错时报错: 分析:这个错误是select into 语句返回多行的结果,但具体在哪? 两种方法查找,trace 或者debug 1.trace 启用调试 获取trace文件 -bash-3. ...
- Android图片色彩变幻
最近在做图片相关的应用,所以就各方积累到一些常用的操作,一般来说会有多种方式来实现这一功能,比如 采用色度变换 采用ColorMatrix颜色矩阵 采用对像素点的直接操作 等等,今天就复习一下第一种方 ...
- Linux Debugging(四): 使用GDB来理解C++ 对象的内存布局(多重继承,虚继承)
前一段时间再次拜读<Inside the C++ Object Model> 深入探索C++对象模型,有了进一步的理解,因此我也写了四篇博文算是读书笔记: Program Transfor ...
- Chipmunk僵尸物理对象的出现和解决(八)
如何解决? 等到碰撞方法返回后在调用Star类方法.碰撞方法在物理引擎的一帧内应该会处理完成,在下一帧里碰撞回调已经结束.所以我们将Star类方法的调用放到下一帧里执行即可,代码如下: //... @ ...