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 ... 
随机推荐
- MySQL数据库内置函数
			mysql数据库中提供了很丰富的函数.mysql函数包括数学函数.字符串函数.日期和时间函数.条件判断函数.系统信息函数.加密函数.格式化函数等.通过这些函数,可以简化用户的操作. 简单介绍几类函数的 ... 
- HTML5 placeholder(空白提示) 属性
			原文地址:HTML5′s placeholder Attribute 演示地址: placeholder演示 原文日期: 2010年08月09日 翻译日期: 2013年8月6日 浏览器引入了许多的HT ... 
- EFI怎么装系统? UEFI BIOS
			关于EFI的介绍,就不赘述了. 大家可以看看这个帖子 http://benyouhui.it168.com/thread-2488583-1-1.html 总之,新电脑都是这玩意,win8也做了相应E ... 
- Android自定义Button的“款式”
			要想让你的button呈现出一种不一样的外观,一般会采取以下两种形式 采用selector里面加图片的方式 采用selector用shape进行代码控制的方式 对第一种方式而言,只需要注意好" ... 
- gitlab6 nginx配置和启动脚本
			gitlab6 nginx配置和启动脚本 cheungmine 2013-10 最近把gitlab安装到了ubuntu12.04.3的虚拟机上了.参考: https://github.com/gitl ... 
- 【Unity Shaders】Reflecting Your World —— 在Unity3D中创建Cubemaps
			本系列主要参考<Unity Shaders and Effects Cookbook>一书(感谢原书作者),同时会加上一点个人理解或拓展. 这里是本书所有的插图.这里是本书所需的代码和资源 ... 
- 分布式进阶(十三)Docker Container间实现数据共享
			sudo docker run -it -v /usr/lib:/usr/lib/dbdata --name dbcontainer-192.168.1.184 ubuntu:14.04 sudo d ... 
- Zookeeper Java客户端API的使用
			1. 原生api 具体查看下面github代码 2. ZkClient ZkClient是Github上一个开源的ZooKeeper客户端.ZkClient在ZooKeeper原生 A ... 
- shell的date命令:使用方法,以及小时、分钟的计算
			shell命令格式严格,不像python那样命令行中可以添加空格.如等号两边无空格.有多余空格错误,日期date命令就是最明显的例子. 命令格式: date [-u] [-d datestr] [-s ... 
- 02_JNI中Java代码调用C代码,Android中使用log库打印日志,javah命令的使用,Android.mk文件的编写,交叉编译
			 1 编写以下案例(下面的三个按钮都调用了底层的C语言): 项目案例的代码结构如下: 2 编写DataProvider的代码: package com.example.ndkpassdata; ... 
