BeautfuiSoup4解析器
BeautifulSoup是一个HTML/XML的解析器,主要的功能是如何解析和提取HTML/XML的数据。
官方文档:http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0
1.BeautifulSoup的安装
BeautifulSoup的安装非常简单简单,使用pip安装即可,在cmd中输入
pip install bs4
之后按回车就可以安装成功了。
2.安装解析器
(1)Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml .根据操作系统不同,可以选择下列方法来安装lxml:
$ apt-get install Python-lxml
$ easy_install lxml
$ pip install lxml
(2)另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib:
$ apt-get install Python-html5lib
$ easy_install html5lib
$ pip install html5lib
下表列出了主要的解析器,以及他们的优缺点。
解析器 |
使用方法 |
优势 |
劣势 |
Python标准库 |
BeautifulSoup(markup, "html.parser") |
|
|
lxml HTML 解析器 |
BeautifulSoup(markup, "lxml") |
|
|
lxml XML 解析器 |
BeautifulSoup(markup, ["lxml-xml"]) BeautifulSoup(markup, "xml")
|
|
|
html5lib |
BeautifulSoup(markup, "html5lib") |
|
|
(3)实例:获取博客标题
from bs4 import BeautifulSoup import requests url = 'http://www.santostang.com/' headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'} r = requests.get(url,headers = headers) soup = BeautifulSoup(r.text,'lxml') first_title = soup.find('h1',class_ = 'post-title').a.text().strip() print('第一篇文章的标题是:',first_title) title_list = soup.find_all('h1',class_ = 'post-title') for i in title_list: title = i.a.text.strip() print('第%s篇文章的标题是:%s' % (i+1,title))
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())
3. 4大对象种类
BeautifulSoup将复杂的的html文档转化成一个复杂的树形结构,每个节点都是Python对象,所有的对象可以归纳为4种。
- Tag
- NavigableString
- BeautifulSoup
- Comment
3.1 Tag
Tag对象与XML或者HTML原生文档中的Tag相同,通俗来说就是文档中的一个个标签,例如:
<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>
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’) print('title标签:',soup.title) # <title>The Dormouse's story</title> print('head标签:',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'>
上面的title、a、p和head等HTML标签加上里面的内容就是Tag,现在我们试着用BeautifulSoup来获取Tag。
我们可以利用soup加上标签名轻松获取这些标签的内容,这些标签的类型是<class 'bs4.element.Tag'>。但是注意的的是,它查找的是在所有内容中第一个符合要求的标签,而不是查询所有的标签。
3.2对于Tag,它有两个重要的属性:name、attrs
(1) name
每个tag都有自己的名字,通过.name来获取。
print(soup.name) # [document] #soup 对象本身比较特殊,它的 name 即为 [document] print(soup.head.name) # head #对于其他内部标签,输出的值便为标签本身的名称 print(soup.p.name)
一个tag可能有很多个属性. tag <b
class="boldest"> 有一个 “class” 的属性,值为 “boldest” . tag的属性的操作方法与字典相同.
(2) attrs
也可以直接”点”取属性, 比如: .attrs :
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>
我们要想获取标签内部的文字。很简单,用 .string 即可,例如
print soup.p.string # The Dormouse's story print type(soup.p.string) # In [13]: <class 'bs4.element.NavigableString'>
3.3 BeautifulSoup
BeautifulSoup 对象表示的是一个文档的内容。大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性。
print(type(soup.name)) # <type 'unicode'> print(soup.name) # [document] print(soup.attrs) # 文档本身的属性为空 # {}
3.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'> print(soup.a.Comment) # None
a 标签里的内容实际上是注释,但是如果我们利用 .string 来输出它的内容时,注释符号已经去掉了。
4. 遍历文档树
4.1 直接子节点:.contents .children 属性
(1) .contents
tag的.content属性可以将子节点一列表的方式输出
print(soup.head.contents) >>>[<title>The Dormouse's story</title>]
(2) .children
它返回的不是一个list,而是一个list的生成器对象
print soup.body.p.children #<list_iterator object at 0x000000000314C4A8> for chd in soup.body.p.children: print(child) 结果: <b>The Dormouse's story1</b> <b>The Dormouse's story2</b> <b>The Dormouse's story3</b> <b>The Dormouse's story4</b>
4.2 所有子孙节点: .descendants 属性
.contents 和 .children 属性仅包含tag的直接子节点,.descendants 属性可以对所有tag的子孙节点进行递归循环,和 children类似,我们也需要遍历获取其中的内容。
soup = BeautifulSoup(html,'lxml') for child in soup.body.p.descendants: print(child) 运行结果: <b>The Dormouse's story1</b> The Dormouse's story1 <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> Tillie <b>The Dormouse's story2</b> The Dormouse's story2 <b>The Dormouse's story3</b> The Dormouse's story3 <b>The Dormouse's story4</b> The Dormouse's story4
4.3 节点内容: .string 属性
如果tag只有一个 NavigableString 类型子节点,那么这个tag可以使用 .string 得到子节点。如果一个tag仅有一个子节点,那么这个tag也可以使用 .string 方法,输出结果与当前唯一子节点的 .string 结果相同。
通俗点说就是:如果一个标签里面没有标签了,那么 .string 就会返回标签里面的内容。如果标签里面只有唯一的一个标签了,那么 .string 也会返回最里面的内容。
5. 搜索文档树
5.1 find_all(name, attrs, recursive, text,**kwargs)
1)name 参数
name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉。
a. 传字符串
最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的<b>
标签:
soup.find_all('b') # [<b>test demo</b>]
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 参数
如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性.
soup.find_all(id='link2') # [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
如果传入 href 参数,Beautiful Soup会搜索每个tag的”href”属性:
soup.find_all(href=re.compile("elsie")) # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
搜索指定名字的属性时可以使用的参数值包括 字符串 , 正则表达式 , 列表, True .
下面的例子在文档树中查找所有包含 id 属性的tag,无论 id 的值是什么:
soup.find_all(id=True) # [<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>]
使用多个指定名字的参数可以同时过滤tag的多个属性:
soup.find_all(href=re.compile("elsie"), id='link1') # [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性:
data_soup = BeautifulSoup('<div data-foo="value">foo!</div>') data_soup.find_all(data-foo="value") # SyntaxError: keyword can't be an expression
但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag: data_soup.find_all(attrs={"data-foo": "value"}) # [<div data-foo="value">foo!</div>]
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"]
6.实例:获取北京安居客网站的二手房信息。
from bs4 import BeautifulSoup from urllib import request,parse,error import json,re,time,random header = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36' } def get_result_page(url): req = request.Request(url, headers=header) resp = request.urlopen(req) print(resp.status) soup = BeautifulSoup(resp.read().decode('utf-8'), 'lxml') url_list = soup.find_all('a', {'class': 'houseListTitle'}) #print(url_list) for urls in url_list: get_result_data(urls.attrs['href']) time.sleep(random.randint(0,2)+random.random()) # 开始进行下一页爬取 try: next_url = soup.find_all('a', {'class': 'aNxt'}) if len(next_url) != 0: # 函数进行递归 get_result_page(next_url[0].attrs['href']) except Exception as e: print(e) print('没有下一页') print(next_url) # 详细页面的信息抓取 def get_result_data(url): req = request.Request(url, headers=header) resp = request.urlopen(req).read().decode('utf-8') soup = BeautifulSoup(resp, 'lxml') house_info = soup.find_all('div', class_ = 'houseInfo-content') #print(house_info) try: house_style = str_repalce(house_info[9].text) # 房屋类型 floor = str_repalce(house_info[10].text) #楼层 zhuanxiu = str_repalce(house_info[11].text) # 装修程度 limit_year = str_repalce(house_info[12].text) # 年限 hot = str_repalce(house_info[13].text) #供热 only_house = str_repalce(house_info[13].text) # 唯一住房 print(house_style,floor,zhuanxiu,limit_year,hot,only_house) except Exception as e: print(e) pass # 进行字符串中空格,换行,tab键的替换及删除字符串两边的空格删除 def str_repalce(s): return str(s).replace(" ", "").replace("\n", "").replace("\t", "").strip() if __name__ == '__main__': url = 'https://beijing.anjuke.com/sale/' get_result_page(url)
7. CSS选择器
这就是另一种与 find_all 方法有异曲同工之妙的查找方法. 按照CSS类名搜索tag的功能非常实用,但标识CSS类名的关键字class在Python中是保留字,使用class做参数会导致语法错误.从Beautiful Soup的4.1.1版本开始,可以通过class_参数搜索有指定CSS类名的tag:
- 写 CSS 时,标签名不加任何修饰,类名前加
.
,id名前加#
- 在这里我们也可以利用类似的方法来筛选元素,用到的方法是
soup.select()
,返回类型是list
(1)通过标签名查找
print soup.select('title') #[<title>The Dormouse's story</title>] print soup.select('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>] print soup.select('b') #[<b>The Dormouse's story</b>]
(2)通过类名查找
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>]
(3)通过 id 名查找
print soup.select('#link1') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
(4)组合查找
组合查找即和写 class 文件时,标签名与类名、id名进行的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,二者需要用空格分开
print soup.select('p #link1') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
直接子标签查找,则使用 >
分隔
print soup.select("head > title") #[<title>The Dormouse's story</title>]
(5)属性查找
查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。
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>]
同样,属性仍然可以与上述查找方式组合,不在同一节点的空格隔开,同一节点的不加空格
print soup.select('p a[href="http://example.com/elsie"]') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
(6) 获取内容
以上的 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()) 结果: <class 'list'> The Dormouse's story The Dormouse's story
实例:爬取百度招聘信息。
from bs4 import BeautifulSoup from urllib import request import json def tencent(): url = 'http://hr.tencent.com/' req = request.Request(url + 'position.php?&start=10#a') resp =request.urlopen(req) resHtml = resp.read() output =open('tencent.json','w') html = BeautifulSoup(resHtml,'lxml') # 创建CSS选择器 result = html.select('tr[class="even"]') result2 = html.select('tr[class="odd"]') result += result2 items = [] for site in result: item = {} name = site.select('td a')[0].get_text() detailLink = site.select('td a')[0].attrs['href'] catalog = site.select('td')[1].get_text() recruitNumber = site.select('td')[2].get_text() workLocation = site.select('td')[3].get_text() publishTime = site.select('td')[4].get_text() item['name'] = name item['detailLink'] = url + detailLink item['catalog'] = catalog item['recruitNumber'] = recruitNumber item['publishTime'] = publishTime items.append(item) print(items) # 禁用ascii编码,按utf-8编码 line = json.dumps(items,ensure_ascii=False) output = open('tencent.json', 'w',encoding='utf-8') output.write(line) output.close() if __name__ == "__main__": tencent()