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 ...
随机推荐
- JAVA获取计算机的IP、名称、操作系统等信息
[java] view plaincopyprint? import java.io.BufferedReader; import java.io.InputStream; import java.i ...
- Android进阶(十三)网络爬虫&json应用
刚开始接触网络爬虫,怎一个"菜"字了得!经过几次的折磨,对其原理以及其中用到的json技术有了大致的了解,故作一总结,供有同样迷惑的朋友参考学习. 自己爬取的网站内容为12306的 ...
- catalina.sh设置JAVA_HOME后还无法解决更换JDK有关问题
catalina.sh设置JAVA_HOME后还无法解决更换JDK问题 表示linux已经安装默认的JDK,需要查找配置文件,更换JDK路径为指定的路径 在root用户下 使用echo $PATH 查 ...
- 用SpriteBuilder简化"耕牛遍地走"的动画效果(一)
这又是一个使用SpriteBuilder带来便捷的例子 原文地址在: http://www.raywenderlich.com/32045/how-to-use-animations-and-spri ...
- ROS(indigo)机器人操作系统学习资料和常用功能包汇总整理(ubuntu14.04LTS)
ROS(indigo)机器人操作系统学习资料和常用功能包汇总整理(ubuntu14.04LTS) 1. 网站资源: ROSwiki官网:http://wiki.ros.org/cn GitHub ...
- 利用编辑距离(Edit Distance)计算两个字符串的相似度
利用编辑距离(Edit Distance)计算两个字符串的相似度 编辑距离(Edit Distance),又称Levenshtein距离,是指两个字串之间,由一个转成另一个所需的最少编辑操作次数.许可 ...
- OJ题:将一个字符串顺序翻转
题目描述 写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串. 之前写过这样的一个程序,用位运算的方法去操作指针,但是那样的方法未免就有点复杂啦,不如用以下这种,简单明了. 程序如下: #i ...
- 学习pthreads,使用属性对象创建结合线程和分离线程
当我们创建了子线程,是让它犹如脱缰之马,信步驰骋,还是如乖巧听话的孩子,时不时教导一下呢?针对这个问题,本文介绍线程的结合和分离,结构分为三个部分,第一部分给出代码示例,第二部分对代码进行讲解,第三部 ...
- css文本样式-css学习之旅(4)
color:颜色derction:方向:line-height:行高:letter-spaceing:字符间距:text-align:对齐方向:text-decoration:装饰:text-inde ...
- (三十一)PickerView自定义视图
例如选择国家,左边是名称右边是国家,不应该使用两列,而是自定义PickerView的一列,可以通过xib来实现. 注意,虽然PickerView也是一列,但是数据源方法是@required,所以必须实 ...