Python爬虫(十四)_BeautifulSoup4 解析器

CSS选择器:BeautifulSoup4

和lxml一样,Beautiful Soup也是一个HTML/XML的解析器,主要的功能也是如何解析和提取HTML/XML数据。

lxml只会局部遍历,而Beautiful Soup是基于HTML DOM的,会载入整个文档,解析整个DOM树,因此时间和内存开销都会大很多,所以性能要低于lxml。
BeautifulSoup用来解析HTML比较简单,API非常人性化,支持CSS选择器、Python标准库中的HTML解析器,也支持lxml的XML解析器。
Beautiful Soup3目前已经停止开发,推荐现在的项目使用Beautiful Soup。使用pip安装即可:pip install beautifulsoup4

官方文档: http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0
|抓取工具|速度|使用难道|安装难度|
|---|---|--|----|
|正则|最快|困难|无(内置)|
|BeautifulSoup|慢|最简单|简单|
|lxml|快|简单|一般|

实例:

首先必须要导入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()

运行结果:

<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 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>
  • 如果我们在IPython2下执行,会看到这样一段警告:
  • 意思是,如果我们没有显示地指定解析器,所以默认使用这个系统的最佳可用HTML解析器("lxml")。如果你在另一个系统中运行这段代码,或者在不同的虚拟环境中,使用不同的解析器造成行为不同。
  • 但是我们可以通过soup = BeautifulSoup(html, "lxml")

四大对象种类

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:

  • 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>

上面的titleheadap等等标签上加上里面包括的内容就是Tag,那么试着使用Beautiful Soup来获取Tags

#-*- 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和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.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即可,例如

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
时间: 2024-08-27 23:34:49

Python爬虫(十四)_BeautifulSoup4 解析器的相关文章

Python爬虫实战四之抓取淘宝MM照片

福利啊福利,本次为大家带来的项目是抓取淘宝MM照片并保存起来,大家有没有很激动呢? 最新动态 更新时间:2015/8/2 最近好多读者反映代码已经不能用了,原因是淘宝索引页的MM链接改了.网站改版了,URL的索引已经和之前的不一样了,之前可以直接跳转到每个MM的个性域名,现在中间加了一个跳转页,本以为可以通过这个页面然后跳转到原来的个性域名,而经过一番折腾发现,这个跳转页中的内容是JS动态生成的,所以不能用Urllib库来直接抓取了,本篇就只提供学习思路,代码不能继续用了. 之后博主会利用其它方

Python爬虫利器四之PhantomJS的用法

前言 大家有没有发现之前我们写的爬虫都有一个共性,就是只能爬取单纯的html代码,如果页面是JS渲染的该怎么办呢?如果我们单纯去分析一个个后台的请求,手动去摸索JS渲染的到的一些结果,那简直没天理了.所以,我们需要有一些好用的工具来帮助我们像浏览器一样渲染JS处理的页面. 其中有一个比较常用的工具,那就是 PhantomJS Full web stack No browser required PhantomJS is a headless WebKit scriptable with a Ja

十四.jQuery解析之浏览器嗅探

Chrome和Safrai使用的是webkit作为内核引擎,因此如果 jQuery.browser.webkit为true,则表示浏览器是chrome或safari; 如果jQuery.browser.mozilla为true,则表示浏览器是MozillaFirefox(火狐); jQuery.browser通过解析navigator.userAgent来获取浏览器类型和版本号,这种技术也称为浏览器的嗅探技术. navigator是全局对象window的属性,指向一个Navigator对象,包含

python标准库configparser配置解析器

1 >>> from configparser import ConfigParser, ExtendedInterpolation 2 >>> parser = ConfigParser(interpolation=ExtendedInterpolation()) 3 >>> # the default BasicInterpolation could be used as well 4 >>> parser.read_string

初学 Python(十四)——生成器

初学 Python(十四)--生成器 初学 Python,主要整理一些学习到的知识点,这次是生成器. # -*- coding:utf-8 -*- ''''' 生成式的作用: 减少内存占有,不用一次性 创建list中所有的元素,而 是在需要的时候创建 ''' #创建generator有2种方式 #第一种将列表表达式中的[]改为()即可 g = (x*x for x in range(10)) print g for n in g: print n #第二种,关键字yield def fab(ma

XML的四种解析器原理及性能比较

转自zsq 1.DOM     DOM 是用与平台和语言无关的方式表示 XML 文档的官方 W3C 标准.DOM 是以层次结构组织的节点或信息片断的集合.这个层次结构允许开发人员在树中寻找特定信息.分析该结构通常需要加载整个文档和构造层次结构,然后才能做任何工作.由于它是基于信息层次的,因而 DOM 被认为是基于树或基于对象的.DOM 以及广义的基于树的处理具有几个优点.    首先,由于树在内存中是持久的,因此可以修改它以便应用程序能对数据和结构作出更改.它还可以在任何时候在树中上下导航,而不

转 Python爬虫入门四之Urllib库的高级用法

静觅 » Python爬虫入门四之Urllib库的高级用法 1.设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Headers 的属性. 首先,打开我们的浏览器,调试浏览器F12,我用的是Chrome,打开网络监听,示意如下,比如知乎,点登录之后,我们会发现登陆之后界面都变化了,出现一个新的界面,实质上这个页面包含了许许多多的内容,这些内容也不是一次性就加载完成的,实质上是执行了好多次请求,一般

Python爬虫(十五)_案例:使用bs4的爬虫

本章将从Python案例讲起:所使用bs4做一个简单的爬虫案例,更多内容请参考:Python学习指南 案例:使用BeautifulSoup的爬虫 我们已腾讯社招页面来做演示:http://hr.tencent.com/position.php?&start=10#a 使用BeautifulSoup4解析器,将招聘网页上的职位名称.职位类别.招聘人数.工作地点.时间.以及每个职位详情的点击链接存储出来. #-*- coding:utf-8 -*- from bs4 import Beautiful

Python爬虫(十二)_XPath与lxml类库

Python学习指南 有同学说,我正则用的不好,处理HTML文档很累,有没有其他的方法? 有!那就是XPath,我们可以用先将HTML文档转换成XML文档,然后用XPath查找HTML节点或元素. 什么是XML XML指可扩展标记语言(Extensible Markup Language) XML是一种标记语言,很类似HTML XML的设计宗旨是传输数据,而非显示数据. XML的标签需要我们自行定义. XML被设计为具有自我描述性. XML是W3C的推荐标准. W3School官方文档:http