python爬虫学习7_Beautiful Soup使用
简介
Beautiful Soup 也是一个HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 数据。
-
Beautiful Soup 是基于HTML DOM的,会载入整个文档,解析整个DOM树
-
BeautifulSoup 用来解析 HTML 比较简单,API非常人性化,支持CSS选择器、Python标准库中的HTML解析器
基础使用:
# -*- coding: UTF-8 -*- 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,'lxml') #打开本地 HTML 文件的方式来创建对象 #soup = BeautifulSoup(open('index.html')) #格式化输出 soup 对象的内容 print (soup.prettify())
四大对象种类
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:
-
Tag
-
NavigableString
-
BeautifulSoup
-
Comment
Tag
Tag 通俗点讲就是 HTML 中的一个个标签,它有两个重要的属性,是 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> del soup.p['class'] # 还可以对这个属性进行删除 print soup.p # <p name="dromouse"><b>The Dormouse's story</b></p>
对tag的操作只能是获取tag的相关信息,而获取不到它所包含的内容。
NavigableString
获取标签中的内容。
print soup.p.string # The Dormouse's story print type(soup.p.string) # In [13]: <class 'bs4.element.NavigableString'>
BeautifulSoup
BeautifulSoup 对象表示的是一个文档的内容。大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型
print type(soup.name) # <type 'unicode'> print soup.name # [document] print soup.attrs # 文档本身的属性为空 # {}
Comment
是一个特殊类型的 NavigableString 对象,其输出的内容不包括注释符号。
文档树的操作
之前的标签获取,是在匹配到对应的标签就进行相应的返回,
输出子节点(.contents ,.children)
# 1、将tag的子节点以列表的方式输出 print soup.head.contents #[<title>The Dormouse's story</title>] # 2、用列表索引来获取它的某一个元素 print soup.head.contents[0] #<title>The Dormouse's story</title> # 3、它是一个 list 生成器对象,通过它来遍历所有子孩子 print soup.head.children #<listiterator object at 0x7f71457f5710> for child in soup.body.children: print child
所有子孙节点(.descendants)
.contents 和 .children 属性仅包含tag的直接子节点,.descendants 属性可以对所有tag的子孙节点进行递归循环
for child in soup.descendants: print child
搜索文档树
find_all
find_all(name, attrs, recursive, text, **kwargs)
搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件。
name:可以查找所有名字为 name 的tag。 attrs:定义一个字典参数来搜索包含特殊属性的tag。 recursive:Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False。 limit: 参数限制返回结果的数量. kwargs:Beautiful Soup 会搜索每个 class 属性为 title 的 tag 。kwargs 接收字符串,正则表达式
# 1、超找为‘b’的tag soup.find_all('b') # [<b>The Dormouse's story</b>] # 2、通过正则查找 import re for tag in soup.find_all(re.compile("^b")): print(tag.name) # 3、通过列表参数超找a标签和b标签 soup.find_all(["a", "b"]) # 4、通过text查找 soup.find_all(text="Elsie") # [u'Elsie']
CSS选择器查找
写 CSS 时:
标签名:不加任何修饰
类名:前加.
id名:前加#
通过这个性质bs4有对应的查找方法soup.select()。
soup.select()
通过标签名查找
print soup.select('title') #[<title>The Dormouse's story</title>]
通过类名查找
print soup.select('.sister') #[<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>]
通过 id 名查找
print soup.select('#link1') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
组合查找
和写 class 文件时,标签名与类名、id名进行的组合原理是一样的。需要用空格分开
print soup.select('p #link1') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
属性查找
加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。
print soup.select('a[class="sister"]') #[<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>] print soup.select('a[href="http://example.com/elsie"]') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
获取内容
以上的 select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text() 方法来获取它的内容。
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()