BeautifulSoup4CSS选择器
和 lxml 一样,Beautiful Soup 也是python的一个HTML/XML的解析器,用它可以方便的从网页中提取数据
lxml 只会局部遍历,而Beautiful Soup 是基于HTML DOM的,会载入整个文档,解析整个DOM树,
因此时间和内存开销都会大很多,所以性能要低于lxml。 BeautifulSoup 用来解析 HTML 比较简单,
API非常人性化,支持CSS选择器、Python标准库中的HTML解析器,也支持 lxml 的 XML解析器。
Beautiful Soup 3 目前已经停止开发,推荐现在的项目使用Beautiful Soup 4。
使用 pip 安装即可: pip install beautifulsoup4 官方文档:http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0
Beautiful Soup支持的解析器
解析器 | 使用方法 | 优势 |
---|---|---|
Python标准库 | BeautifulSoup(markup,‘html.parser’) | Python的内置标准库、执行速度适中、文档容错能力强 |
lxml HTML解析器 | BeautifulSoup(markup,‘lxml’) | 速度快、文档容错能力强 |
lxml XML解析器 | BeautifulSoup(markup,‘xml’) | 速度快、唯一支持XML的解析器 |
html5lib | BeautifulSoup(markup,‘html5lib’) | 最好的容错性、以浏览器的方式解析文档,生成HTML5的格式文档 |
四大对象种类
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:
- Tag
- NavigableString
- BeautifulSoup
- Comment
1.Tag:
Tag 通俗点讲就是 HTML 中的一个个标签,例如:
<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等等 HTML 标签加上里面包括的内容就是 Tag,那么试着使用 Beautiful Soup 来获取 Tags:
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.head)
# <head><title>The Dormouse's story</title></head>
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 和 attrs
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.p['class'] = "newClass"
print soup.p
# 可以对这些属性和内容等等进行修改 # <p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>
2.NavigableString
既然我们已经得到了标签的内容,那么问题来了,我们要想获取标签内部的文字怎么办呢?很简单,用 .string 即可,例如
print (soup.p.string)
# The Dormouse's story
print (type(soup.p.string))
# In [13]: <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. find_all(name, attrs, recursive, text, **kwargs)
1)name 参数
name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉
- A.传字符串
最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的标签:
soup.find_all(name='b')
soup.find_all(name='a')
- C.传列表
- 如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有标签和标签:
soup.find_all(["a", "b"])
2)attr 参数
soup.find_all(attrs={'id':'link2'})
soup.find_all(attrs={'class':'link2'})
3) keyword 参数
soup.find_all(id='link2')
soup.find_all(class_='link3')
2. CSS选择器
这就是另一种与 find_all 方法有异曲同工之妙的查找方法.写 CSS 时,标签名不加任何修饰,类名前加.,id名前加#在这里我们也可以利用类似的方法来筛选元素,用到的方法是soup.select(),返回类型是 list
表达式 | 说明 |
---|---|
* | 选择所有节点 |
#container | 选择id为container的节点 |
.container | 选取所有class包含container的节点 |
li a | 选取所有li下的所有a节点 |
div#container > ul | 选取id为container的div的ul子元素 |
a[href=“http://jobbole.com”] | 选取所有href属性为jobbole.com值的a元素 |
a[href*=”jobole”] | 选取所有href属性包含jobbole的a元素 |
a[href^=“http”] | 选取所有href属性值以http开头的a元素 |
a[href$=“.jpg”] | 选取所有href属性值以.jpg结尾的a元素 |
div:not(#container) | 选取所有id非container的div属性 |
li:nth-child(3) | 选取第三个li元素 |
tr:nth-child(2n) | 第偶数个tr |
1)通过标签名查找
soup.select('title')
soup.select('b')
2)通过类名查找
print soup.select('.sister'))
3)通过 id 名查找
print soup.select('#link1')
4)组合查找
组合查找即和写 class 文件时,标签名与类名、id名进行的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,二者需要用空格分开
print soup.select('p #link1')
直接子标签查找,则使用 > 分隔
print soup.select("head > title")
5)属性查找
查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。
print(soup.select('a[class="sister"]'))
soup.select('a[href="http://example.com/elsie"]')
同样,属性仍然可以与上述查找方式组合,不在同一节点的空格隔
开,同一节点的不加空格
print (soup.select('p a[href="http://example.com/elsie"]'))
6) 获取内容
以上的 select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text() 方法来获取它的内容,attrs[‘属性名’] 获取属性值
soup = BeautifulSoup(html, 'lxml')
print (type(soup.select('title')))
print (soup.select('title')[0].get_text())
for title in soup.select('title'):
print (title.get_text())
print (title.attrs['class'])