爬虫库之BeautifulSoup学习(一)

Beautiful Soup的简介

  简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。

  官方解释如下:

  Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。

  Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。

  Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。

     

  Beautiful Soup 相比其他的html解析有个非常重要的优势。html会被拆解为对象处理。全篇转化为字典和数组

  相比正则解析的爬虫,省略了学习正则的高成本。

  相比xpath爬虫的解析,同样节约学习时间成本。虽然xpath已经简单点了。(爬虫框架Scrapy就是使用xpath)

 

 

安装:

  Beautiful Soup 3 目前已经停止开发,推荐在现在的项目中使用Beautiful Soup 4,不过它已经被移植到BS4了,也就是说导入时我们需要 import bs4 。所以这里我们用的版本是 Beautiful Soup 4.3.2 (简称BS4)。

  pip方式安装:pip install BeautifulSoup

  easy_install来安装: easy_install beautifulsoup4

 

导入:

  from bs4 import BeautifulSoup

 

小试手刀:

  import requests

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

  soup = BeautifulSoup(html,'html.parser')

  print soup.body()

 

  运行结果: 

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

[Finished in 0.2s]

 

 

  注:本学习摘录了:http://cuiqingcai.com/1319.html  部分内容。

 

posted @ 2017-05-11 11:54  沉默的云  阅读(245)  评论(0编辑  收藏  举报