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 ...
随机推荐
- 应用UUID简化设计
应用UUID简化设计(金庆的专栏)UUID(Universally Unique Identifier) 保证每次生成的都是唯一的,不同机器生成UUID也能保证唯一.网游中使用UUID可以避免全局的I ...
- 【FPGA学习】Verilog之加法器
在fpga工程应用设计中,随处可见加法器,乘法器等等.现在将一些常用模块和心得体会先记录下来,以便日后使用. 一位半加器: module halfadder(cout,sum,a,b); output ...
- ROS_Kinetic_12 ROS程序基础Eclipse_C++(三)usb camera
ROS_Kinetic_12 ROS程序基础Eclipse_C++(三)usb camera 软件包下载地址:https://github.com/bosch-ros-pkg/usb_cam 下载后, ...
- UIPassValue页面传值 UI_08(下)
2.从前一个界面到后一个界面 注意:解题思路 葵花宝典:属性传值 第一步:在下一个界面视图控制器的.h文件中定义一个属性 第二步:在push之前将数据存储到属性中 第三步:取出属性中的值让控件 ...
- Linux IPC实践(4) --System V消息队列(1)
消息队列概述 消息队列提供了一个从一个进程向另外一个进程发送一块数据的方法(仅局限于本机); 每个数据块都被认为是有一个类型,接收者进程接收的数据块可以有不同的类型值. 消息队列也有管道一样的不足: ...
- ZooKeeper 实现分布式队列
使用场景 在传统的单进程编程中,我们使用队列来存储数据结构,用来在多线程之间共享或者传递数据.在分布式环境下,同样需要一个类似单进程的组件, 用来实现跨进程.跨主机.跨网络的数据共享和数据传递.这就 ...
- nginx 配置open_cache_file 静态文件的缓存
open_file_cache max=65535 inactive=30s 最多缓存多少个文件,缓存多少时间open_file_cache_min_uses 1 在30S中没有使用到这个配置的次数的 ...
- 简单说说Android自定义view学习推荐的方式
这几天比较受关注,挺开心的,嘿嘿. 这里给大家总结一下学习自定义view的一些技巧. 以后写自定义view可能不会写博客了,但是可以开源的我会把源码丢到github上我的地址:https://git ...
- 理解WebKit和Chromium: Chromium网络栈
转载请注明原文地址:http://blog.csdn.net/milado_nju ## 概述 前面讲到Chromium的资源加载机制,在调用栈上,提到URLRequest之后就戛然而止,在这之下就是 ...
- [Python]Flask构建网站分析应用
原文Saturday morning hacks: Building an Analytics App with Flask - 由orangleliu友情翻译 ,主要是通过埋点技术来实现web网页的 ...