BeautifulSoup基本步骤

 

http://blog.csdn.net/kikaylee/article/details/56841789css

 

’BeautifulSoup是Python的一个库,最主要的功能就是从网页爬取咱们须要的数据。BeautifulSoup将html解析为对象进行处理,所有页面转变为字典或者数组,相对于正则表达式的方式,能够大大简化处理过程。html

0x01 安装

建议安装BeautifulSoup 4版本 利用pip进行安装:python

pip install beautifulsoup4
  • 1

BeautifulSoup默认支持Python的标准HTML解析库,可是它也支持一些第三方的解析库:正则表达式

序号 解析库 使用方法 优点 劣势
1 Python标准库 BeautifulSoup(html,’html.parser’) Python内置标准库;执行速度快 容错能力较差
2 lxml HTML解析库 BeautifulSoup(html,’lxml’) 速度快;容错能力强 须要安装,须要C语言库
3 lxml XML解析库 BeautifulSoup(html,[‘lxml’,’xml’]) 速度快;容错能力强;支持XML格式 须要C语言库
4 htm5lib解析库 BeautifulSoup(html,’htm5llib’) 以浏览器方式解析,最好的容错性 速度慢

0x02 建立对象

导入库:数据库

from bs4 import BeautifulSoup
  • 1

建立实例:数组

url='http://www.baidu.com' resp=urllib2.urlopen(url) html=resp.read()
  • 1
  • 2
  • 3

建立对象:浏览器

 bs=BeautifulSoup(html)
  • 1
  • 2

格式化输出内容:app

print bs.prettify()
  • 1

0x03 对象种类

BeautifulSoup将复杂的html文档转换为树形结构,每个节点都是一个对象,这些对象能够概括为几种:ui

(1)Taglua

Tag至关于html种的一个标签:

#提取Tag print bs.title print type(bs.title)
  • 1
  • 2
  • 3

结果:

<title>百度一下,你就知道</title> <class 'bs4.element.Tag'>
  • 1
  • 2

对于Tag,有几个重要的属性:

name:每一个Tag对象的name就是标签本省的名称; 
attrs:每一个Tag对象的attrs就是一个字典,包含了标签的所有属性。

print bs.a.name print bs.a.attrs
  • 1
  • 2

输出:

a
{u'href': u'/', u'id': u'result_logo', u'onmousedown': u"return c({'fm':'tab','tab':'logo'})"}
  • 1
  • 2

(2)NavigableString

Comment是一种特殊的NavigableString,对应的是注释的内容,可是其输出不包含注释符。看这样的一个例子:

#coding:utf-8 from bs4 import BeautifulSoup html=''' <a class="css" href="http://example.com/test" id="test"><!--test --></a> ''' bs=BeautifulSoup(html,"html.parser") print bs.a print bs.a.string
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

运行结果:

<a class="css" href="http://example.com/test" id="test"><!--def --></a>
  • 1

a标签的内容是注释,可是使用.string仍然输出了。这种状况下,咱们须要作下判断:

#判断是不是注释 if type(bs.a.string)==element.Comment: print bs.a.string
  • 1
  • 2
  • 3

再看下面的例子:

<a class="css1" href="http://example.com/cdd" id="css">abc<!--def -->gh</a>
  • 1

内容是注释和字符串混合,此时能够用contents获取所有对象:

for i in bs.a.contents: print i
  • 1
  • 2

若是须要忽略注释内容的话,能够利用get_text()或者.text:

print bs.a.get_text()
  • 1

若是想在BeautifulSoup以外使用 NavigableString 对象,须要调用unicode()方法,将该对象转换成普通的Unicode字符串,不然就算BeautifulSoup已方法已经执行结束,该对象的输出也会带有对象的引用地址,这样会浪费内存。

0x04 搜索文档树

重点介绍下find_all()方法:

find_all( name , attrs , recursive , text , **kwargs )
  • 1

(1)name参数

name参数能够查找全部名字为name的Tag,字符串对象自动忽略掉。

print bs.find_all('a')
  • 1

传列表:

print bs.find_all(['a','b'])
  • 1

传入正则表达式:

print bs.find_all(re.compile('^b'))
  • 1

全部以b开头的标签对象都会被找到。 
传递方法:

def has_class_but_not_id(tag): return tag.has_attr('class') and not tag.has_attr('id') print bs.find_all(has_class_but_not_id)
  • 1
  • 2
  • 3

(2)kwyowrds关键字

print bs.find_all(id='css') print bs.find_all(id=re.compile('^a'))
  • 1
  • 2

还能够混合使用:

print bs.find_all(id='css',href=re.compile('^ex'))
  • 1

可使用class做为过滤,可是class是Python中的关键字,可使用class_代替,或者采用字典的形式传输参数:

print bs.find_all(class_='css') print bs.find_all(attrs={'class':'css'})
  • 1
  • 2

(3)text参数

用来搜索文档中的字符串内容,text参数也接收字符串、正则表达式、列表、True等参数。

print bs.find_all(text=re.compile('^abc'))
  • 1

(4)limit参数

限制返回对象的个数,与数据库SQL查询相似。

(5)recursive参数

调用tag的find_all()方法时,BeautifulSoup会检索当前tag的全部子孙节点,若是只想搜索tag的直接子节点,可使用参数 recursive=False。

0x05 CSS选择器

能够采用CSS的语法格式来筛选元素:

#标签选择器 print bs.select('a') #类名选择器 print bs.select('.css') #id选择器 print bs.select('#css') #属性选择器 print bs.select('a[class="css"]') #遍历 for tag in bs.select('a'): print tag.get_text()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

对于喜欢用CSS语法的人来讲,这种方式很是方便。若是你仅仅须要CSS选择器的功能,那么直接使用 lxml 也能够,并且速度更快,支持更多的CSS选择器语法,但Beautiful Soup整合了CSS选择器的语法和自身方便使用API。

相关文章
相关标签/搜索