CSS选择器:BeautifulSoup4
和lxml同样,Beautiful Soup也是一个HTML/XML的解析器,主要的功能也是如何解析和提取HTML/XML数据。css
lxml只会局部遍历,而Beautiful Soup是基于HTML DOM的,会载入整个文档,解析整个DOM树,所以时间和内存开销都会大不少,因此性能要低于lxml。
BeautifulSoup用来解析HTML比较简单,API很是人性化,支持CSS选择器、Python标准库中的HTML解析器,也支持lxml的XML解析器。
Beautiful Soup3目前已经中止开发,推荐如今的项目使用Beautiful Soup。使用pip安装便可:pip install beautifulsoup4
html
官方文档: http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0
|抓取工具|速度|使用难道|安装难度|
|---|---|--|----|
|正则|最快|困难|无(内置)|
|BeautifulSoup|慢|最简单|简单|
|lxml|快|简单|通常|python
实例:
首先必需要导入bs4库正则表达式
# 07-urllib2_beautipulsoup_prettify from bs4 import BeautifulSoup 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" 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> """ #建立 Beautiful Soup 对象 soup = BeautifulSoup(html) #打开本地 HTML 文件的方式来建立对象 #soup = BeautifulSoup(open('index.html')) #格式化输出 soup 对象的内容 print soup.prettify()
- 若是咱们在IPython2下执行,会看到这样一段警告:
- 意思是,若是咱们没有显示地指定解析器,因此默认使用这个系统的最佳可用HTML解析器("lxml")。若是你在另外一个系统中运行这段代码,或者在不一样的虚拟环境中,使用不一样的解析器形成行为不一样。
- 可是咱们能够经过
soup = BeautifulSoup(html, "lxml")
四大对象种类
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每一个节点都是Python对象,全部对象能够概括为4种:markdown
- Tag
- NaviganleString
- BeautifulSoup
- Comment
1.Tag
Tag通俗点讲就是HTM中的一个个标签,例如:工具
<head><title>The Dormouse's story</title></head> <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
上面的title
、head
、a
、p
等等标签上加上里面包括的内容就是Tag,那么试着使用Beautiful Soup来获取Tagspost
#-*- coding:utf-8 -*- #08-urllib2_beautifulsoup_tag.py from bs4 import BeautifulSoup 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" 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> """ #建立Beautiful Soup对象 soup = BeautifulSoup(html) print soup.title #<title>The Dormouse's story</title> print soup.a #<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> print soup.p #<p class="title" name="dromouse"><b>The Dormouse's story</b></p> print type(soup.p) # <class 'bs4.element.Tag'>
咱们能够利用 soup 加标签名轻松地获取这些标签的内容,这些对象的类型是bs4.element.Tag
。可是注意,它查找的是在全部内容中的第一个符合要求的标签。若是要查询全部的标签,后面会进行介绍。性能
对于Tag,它有两个重要的属性,是name和attrsurl
print soup.name #[document] #soup对象自己比较特殊,它的name即为[document] print soup.head.name #head #对于其余内部标签,输出的值便为标签自己的名称 print soup.p.attrs #{'class':['title'], 'name':'dromouse'} #在这里,咱们把p标签的全部属性打印出来,获得的类型是一个字典 print soup.p['class'] #soup.p.get('class') #['title'] #还能够利用get方法,传入属性的方法,两者是等价的。 soup.a['class'] = 'newClass' print soup.p #能够对这些属性和内容等等进行修改 # <p class="newClass" name="dromouse"><b>The Dormouse's story</b></p> del soup.p['class'] #还能够对这个属性进行删除 print soup.p # <p name="dromouse"><b>The Dormouse's story</b></p>
2. NavigableString
既然咱们已经获得了标签的内容,那么问题来了,咱们要想获取标签内部的文字怎么办呢?很简单,用.string便可,例如spa
print soup.p.string #The Dormouse's story print type(soup.p.string) <class 'bs4.element.NavigableString'>
3. BeautifulSoup
BeautifulSoup对象表示的是一个文档的内容。大部门时候,能够用它当作Tag对象,是一个特殊的Tag,咱们能够分别获取它的类型,名称,以及属性来感觉一下。
print type(soup.name) #<type 'unicode'> print soup.name #[document] print soup.attrs #文档自己的属性为空 #{}
4. Comment
Comment对象时一个特殊类型的NavigableString对象,其输出的内容不包括注释符号。
print soup.a # <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> print soup.a.string #Elsie print type(soup.a.string) # <class 'bs4.element.Comment'>
a标签里的内容其实是注释,可是若是咱们利用.string来输出它的内容时,注释符号已经去掉了。
遍历文档树
1.直接子节点:.contents
.children
属性
.content
tag的.content属性能够将tag的子节点以列表的方式输出。
print soup.head.contents #[<title>The Dormouse's story</title>]
输出方式为列表,咱们能够用列表索引来获取它的某一个元素
print soup.head.contents[0] #<title>The Dormouse's story</title>
.children
它返回的不是一个list,不过咱们能够经过遍历获取全部子节点。
咱们打印输出.children看一下,能够发现他是一个list生成器对象。
print soup.head.children #<listiterator object at 0x7f71457f5710> for child in soup.body.children: print child
结果:
<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" 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>
2. 全部子孙节点:.descendants
属性
.contents和.children属性仅包含tag的直接子节点,.descendants属性能够对全部tag的子孙节点进行递归循环,和.children相似,咱们也须要遍历获取其中的内容。
for child in soup.descendants: print child
3. 节点内容:.string
属性
若是tag只有一个NavigableString类型子节点,那么这个tag能够使用.string获得子节点。若是一个tag仅有一个子节点,那么这个tag也能够使用.string,输出结果与当前惟一子节点的.string
结果相同。
通俗点讲就是:若是一个标签里面没有标签了,那么.string就会返回标签里面的内容。若是标签里面只有惟一的一个标签了,那么.string也会返回最里面的内容。例如:
print soup.head.string #The Dormouse's story print soup.title.string #The Dormouse's story
搜索文档树
1. find_all(name, attrs, recursive, text, **kwargs)
1) name参数
name参数能够查找全部民资为name的tag,字符串对象会自动忽略掉。
A.传字符串
最简单的过滤器是字符串,在搜索方法中传入一个字符串参数,eautiful Soup会自动查找与字符串完整匹配的内容,下面的例子用于查找文档中全部的标签:
soup.find_all('b') #[<b>The Dormouse's story</b>] print soup.find_all('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>]
B.传正则表达式
若是传入正则表达式做为参数,Beautiful Soup会经过正则表达式的match()来匹配内容。下面例子中找出全部以b开头的标签,这表示<body>
和<b>
标签都应该被找到。
import re for tag in soup.find_all(re.compile('^b')): print(tag.name) #body #b
C.传列表
若是传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回 下面代码找到文档中全部<a>
标签和<b>
标签:
soup.find_all(['a', 'b']) # [<b>The Dormouse's story</b>, # <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>]
2) keyword参数
soup.find_all(id='link2') # [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
3) text参数
经过text参数能够搜索文档中的字符串内容,与name参数的可选值同样,text参数接收参数值,正则表达式,列表
soup.find_all(text='Elsie') #[u'Elsie'] soup.find_all(text=['Tillie', 'Elsie', 'Lacie']) # [u'Elsie', u'Lacie', u'Tillie'] soup.find_all(text=re.compile("Dormouse")) [u"The Dormouse's story", u"The Dormouse's story"]
CSS选择器
这就是另外一种与 find_all 方法有殊途同归之妙的查找方法.
- 写 CSS 时,标签名不加任何修饰,类名前加.,id名前加#
- 在这里咱们也能够利用相似的方法来筛选元素,用到的方法是
soup.select()
,返回类型是list