原文地址http://blog.csdn.net/watsy/article/details/14161201

先发一下官方文档地址。http://www.crummy.com/software/BeautifulSoup/bs4/doc/

建议有时间可以看一下python包的文档。

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

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

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

安装
linux下可以执行

[plain] view plaincopy
apt-get install python-bs4

也可以用python的安装包工具来安装
[html] view plaincopy
easy_install beautifulsoup4

pip install beautifulsoup4

使用简介
下面说一下BeautifulSoup 的使用。

解析html需要提取数据。其实主要有几点

1:获取指定tag的内容。

[plain] view plaincopy

hello, watsy

hello, beautiful soup.

2:获取指定tag下的属性。

[html] view plaincopy
watsy's blog
3:如何获取,就需要用到查找方法。

使用示例采用官方

[html] view plaincopy
html_doc = """
The Dormouse's story

The Dormouse's story

Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well.

...

"""
格式化输出。
[html] view plaincopy
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)

print(soup.prettify())

The Dormouse's story

The Dormouse's story

Once upon a time there were three little sisters; and their names were

Elsie

,

Lacie

and

Tillie

; and they lived at the bottom of a well.

...

获取指定tag的内容
[html] view plaincopy
soup.title

The Dormouse's story

soup.title.name

u'title'

soup.title.string

u'The Dormouse's story'

soup.title.parent.name

u'head'

soup.p

The Dormouse's story

soup.a

Elsie

上面示例给出了4个方面
1:获取tag

soup.title

2:获取tag名称

soup.title.name

3:获取title tag的内容

soup.title.string

4:获取title的父节点tag的名称

soup.title.parent.name

怎么样,非常对象化的使用吧。

提取tag属性
下面要说一下如何提取href等属性。

[html] view plaincopy
soup.p['class']

u'title'

获取属性。方法是
soup.tag['属性名称']

[html] view plaincopy
watsy's blog
常见的应该是如上的提取联接。
代码是

[html] view plaincopy
soup.a['href']
相当easy吧。

查找与判断
接下来进入重要部分。全文搜索查找提取.

soup提供find与find_all用来查找。其中find在内部是调用了find_all来实现的。因此只说下find_all

[html] view plaincopy
def find_all(self, name=None, attrs={}, recursive=True, text=None,
limit=None, **kwargs):

看参数。
第一个是tag的名称,第二个是属性。第3个选择递归,text是判断内容。limit是提取数量限制。**kwargs 就是字典传递了。。

举例使用。

[html] view plaincopy
tag名称
soup.find_all('b')

[The Dormouse's story]

正则参数
import re
for tag in soup.find_all(re.compile("^b")):
print(tag.name)

body

b

for tag in soup.find_all(re.compile("t")):
print(tag.name)

html

title

列表
soup.find_all(["a", "b"])

[The Dormouse's story,

Elsie,

Lacie,

Tillie]

函数调用
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')

soup.find_all(has_class_but_no_id)

[

The Dormouse's story

,

Once upon a time there were...

,

...

]

tag的名称和属性查找
soup.find_all("p", "title")

[

The Dormouse's story

]

tag过滤
soup.find_all("a")

[Elsie,

Lacie,

Tillie]

tag属性过滤
soup.find_all(id="link2")

[Lacie]

text正则过滤
import re
soup.find(text=re.compile("sisters"))

u'Once upon a time there were three little sisters; and their names were\n'

获取内容和字符串
获取tag的字符串
[html] view plaincopy
title_tag.string

u'The Dormouse's story'

注意在实际使用中应该使用 unicode(title_tag.string)来转换为纯粹的string对象

使用strings属性会返回soup的构造1个迭代器,迭代tag对象下面的所有文本内容
[html] view plaincopy
for string in soup.strings:
print(repr(string))

u"The Dormouse's story"

u'\n\n'

u"The Dormouse's story"

u'\n\n'

u'Once upon a time there were three little sisters; and their names were\n'

u'Elsie'

u',\n'

u'Lacie'

u' and\n'

u'Tillie'

u';\nand they lived at the bottom of a well.'

u'\n\n'

u'...'

u'\n'

获取内容
.contents会以列表形式返回tag下的节点。
[html] view plaincopy
head_tag = soup.head
head_tag

The Dormouse's story

head_tag.contents
[The Dormouse's story]

title_tag = head_tag.contents[0]
title_tag

The Dormouse's story

title_tag.contents

[u'The Dormouse's story']

想想,应该没有什么其他的了。。其他的也可以看文档学习使用。

总结
其实使用起主要是
[html] view plaincopy
soup = BeatifulSoup(data)
soup.title
soup.p.['title']
divs = soup.find_all('div', content='tpc_content')
divs[0].contents[0].string

[转]python下很帅气的爬虫包 - Beautiful Soup 示例的更多相关文章

  1. python下很帅气的爬虫包 - Beautiful Soup 示例

    先发一下官方文档地址.http://www.crummy.com/software/BeautifulSoup/bs4/doc/ 建议有时间可以看一下python包的文档. Beautiful Sou ...

  2. python下的复杂网络编程包networkx的安装及使用

    由于py3.x与工具包的兼容问题,这里采用py2.7 1.python下的复杂网络编程包networkx的使用: http://blog.sina.com.cn/s/blog_720448d30101 ...

  3. python 爬虫利器 Beautiful Soup

    python 爬虫利器 Beautiful Soup Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文 ...

  4. Python爬虫之Beautiful Soup解析库的使用(五)

    Python爬虫之Beautiful Soup解析库的使用 Beautiful Soup-介绍 Python第三方库,用于从HTML或XML中提取数据官方:http://www.crummv.com/ ...

  5. [Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息

    [Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息 2018-07-21 23:53:02 larger5 阅读数 4123更多 分类专栏: 网络爬虫   版权声明: ...

  6. python爬虫之Beautiful Soup基础知识+实例

    python爬虫之Beautiful Soup基础知识 Beautiful Soup是一个可以从HTML或XML文件中提取数据的python库.它能通过你喜欢的转换器实现惯用的文档导航,查找,修改文档 ...

  7. python下的复杂网络编程包networkx的使用(摘抄)

    原文:http://blog.sciencenet.cn/home.php?mod=space&uid=404069&do=blog&classid=141080&vi ...

  8. python爬虫之Beautiful Soup的基本使用

    1.简介 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据.官方解释如下: Beautiful Soup提供一些简单的.python式的函数用来处理导航.搜索 ...

  9. Python爬虫库-Beautiful Soup的使用

    Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库,简单来说,它能将HTML的标签文件解析成树形结构,然后方便地获取到指定标签的对应属性. 如在上一篇文章通过爬虫 ...

随机推荐

  1. Jdk命令之jps

    jps -- Java Virtual Machine Process Status Tool jps命令类似于Linux下的ps命令,可以列出本机所有正在运行的java进程.

  2. java.util.regex.PatternSyntaxException: Unclosed character class near index解决办法

    使用str.split("[")时,出现java.util.regex.PatternSyntaxException: Unclosed character class near  ...

  3. 值得珍藏的.NET源码,不保存就没机会了

    很早以前,我们通过http://referencesource.microsoft.com/netframework.aspx可以下载到.NET的各版本公开源码,但如今,微软对sscli项目进行了改版 ...

  4. spring cloud config 入门

    简介 Spring cloud config 分为两部分 server client config-server 配置服务端,服务管理配置信息 config-client 客户端,客户端调用serve ...

  5. orzdba在5.6安装

    前言:淘宝的orzdba查看MySQL服务器当前QPS,TPS很方便,但是不少人反应,在5.6原本好用的工具不好用了,频繁出现这样警告: Warning: Using a password on th ...

  6. javascript 字符转义汇总

    在开发中经常遇到需要字符转义的,我将一一把遇到的转义列举出来 1.今天中午做项目的时候遇到一个字符串链接的问题,需要链接的的是一个函数的参数 时间字符串:"2014-04-08 16:37: ...

  7. Ubuntu中Eclipse安装与配置

    安装Eclipse: 第一种是通过Ubuntu自带的程序安装功能安装Eclipse,应用程序 ->Ubtuntu软件中心,搜Eclipse安装即可.第二种方法是用命令:应用程序->附件-& ...

  8. Codeforces Round #239 (Div. 2)

    做了三个题,先贴一下代码...终于涨分了 A. Line to Cashier 水题 #include <iostream> #include <cstdio> #includ ...

  9. bzoj1913

    这是一道好题,要求每个三点圆覆盖的点数和 我们可以算四边形的贡献,四边形显然分成两种:凸四边形和凹四边形 显然,凹四边形的覆盖只可能是三个点组成三角形包含另一个点,所以贡献是1 凸四边形,其最小圆覆盖 ...

  10. UVa 10674 (求两圆公切线) Tangents

    题意: 给出两个圆的圆心坐标和半径,求这两个圆的公切线切点的坐标及对应线段长度.若两圆重合,有无数条公切线则输出-1. 输出是按照一定顺序输出的. 分析: 首先情况比较多,要一一判断,不要漏掉. 如果 ...