背景

在Python去写爬虫,网页解析等过程中,比如:

如何用Python,C#等语言去实现抓取静态网页+抓取动态网页+模拟登陆网站

常常需要涉及到HTML等网页的解析。

当然,对于简单的HTML中内容的提取,Python内置的正则表达式Re模块,就足够用了,

但是对于复杂的HTML的处理,尤其是一些非法的,有bug的html代码的处理,那么最好还是用专门的HTML的解析的库。

Python中的,专门用于HTML解析的库,比较好用的,就是BeautifulSoup。

BeautifulSoup简介

Python中,专门用于HTML/XML解析的库;

特点是:

即使是有bug,有问题的html代码,也可以解析。

功能很强大;

BeautifulSoup的主页是:

http://www.crummy.com/software/BeautifulSoup/

BeautifulSoup的版本

BeautifulSoup主要有两个版本:

BeautifulSoup 3

之前的,比较早的,是3.x的版本。

BeautifulSoup 3的在线文档

最新的,可用的,在线文档是:

http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html

中文版的是:

http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html

下载BeautifulSoup 3

http://www.crummy.com/software/BeautifulSoup/bs3/download//3.x/

中可以下载到很多版本,比如我常用的3.0.6的版本:

BeautifulSoup-3.0.6.py

http://www.crummy.com/software/BeautifulSoup/bs3/download//3.x/BeautifulSoup-3.0.6.py

BeautifulSoup 4:缩写为bs4

最新的v4版本的BeautifulSoup,改名为bs4了。

注意:

使用bs4时,导入BeautifulSoup的写法是:

1
from bs4 import BeautifulSoup;

然后就可以像之前3.x中一样,直接使用BeautifulSoup了。

详见:

【已解决】Python3中,已经安装了bs4(Beautifulsoup 4)了,但是却还是出错:ImportError: No module named BeautifulSoup

bs4的在线文档

http://www.crummy.com/software/BeautifulSoup/bs4/doc/

下载bs4

http://www.crummy.com/software/BeautifulSoup/bs4/download/

可以下载到对应的bs4的版本,比如:

此时最新的版本是:

beautifulsoup4-4.1.3.tar.gz

http://www.crummy.com/software/BeautifulSoup/bs4/download/beautifulsoup4-4.1.3.tar.gz

BeautifulSoup的用法

如何安装BeautifulSoup

3.0.6之前:无需安装,放到和Python文件同目录下即可使用

3.0.6之前,都是不需要安装的,所以使用起来最简单,直接下载对应的版本,比如:

http://www.crummy.com/software/BeautifulSoup/bs3/download//3.x/BeautifulSoup-3.0.6.py

得到了BeautifulSoup-3.0.6.py,然后改名为:BeautifulSoup.py

然后,放到和你当前的python文件同目录下,比如我当前python文件是:

D:\tmp\tmp_dev_root\python\beautifulsoup_demo\beautifulsoup_demo.py

那就放到

D:\tmp\tmp_dev_root\python\beautifulsoup_demo\

下面,和beautifulsoup_demo.py同目录。

3.0.6之后:需要安装BeautifulSoup后才可使用

关于如何安装一个Python的第三方模块,简单说就是,进入对应目录,运行:

1
setup.py install

详细解释可参考:

【总结】Python安装第三方的库、package的方法

如何使用BeautifulSoup

在你的Python文件,此处为beautifulsoup_demo.py,中直接import即可。

关于示例html代码,比如使用:

【教程】抓取网并提取网页中所需要的信息 之 Python版

相关参考文档:

3.x版本的:

find(name, attrs, recursive, text, **kwargs)

使用BeautifulSoup提取html中的某个内容

关于最简单的,最基本的用法,提取html中的某个内容,具体用法,就死使用对应的find函数。

完整代码是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【教程】Python中第三方的用于解析HTML的库:BeautifulSoup
 
 
Author:     Crifan Li
Version:    2012-12-26
Contact:    admin at crifan dot com
"""
 
from BeautifulSoup import BeautifulSoup;
 
def beautifulsoupDemo():
    demoHtml = """
<html>
<body>
<div class="icon_col">
        <h1 class="h1user">crifan</h1>
 </div>
 </body>
</html>
""";
    soup = BeautifulSoup(demoHtml);
    print "type(soup)=",type(soup); #type(soup)= <type 'instance'>
    print "soup=",soup;
     
    # 1. extract content
    # method 1: no designate para name
    #h1userSoup = soup.find("h1", {"class":"h1user"});
    # method 2: use para name
    h1userSoup = soup.find(name="h1", attrs={"class":"h1user"});
    # more can found at:
    #http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html#find%28name,%20attrs,%20recursive,%20text,%20**kwargs%29
    print "h1userSoup=",h1userSoup; #h1userSoup= <h1 class="h1user">crifan</h1>
    h1userUnicodeStr = h1userSoup.string;
    print "h1userUnicodeStr=",h1userUnicodeStr; #h1userUnicodeStr= crifan
 
if __name__ == "__main__":
    beautifulsoupDemo();

输出为:

1
2
3
4
5
6
7
8
9
10
11
12
13
D:\tmp\tmp_dev_root\python\beautifulsoup_demo>beautifulsoup_demo.py
type(soup)= <type 'instance'>
soup=
<html>
<body>
<div class="icon_col">
<h1 class="h1user">crifan</h1>
</div>
</body>
</html>
 
h1userSoup= <h1 class="h1user">crifan</h1>
h1userUnicodeStr= crifan

使用BeautifulSoup修改/改变/替换原先html中的某个内容

如果需要改变原先html中的某个值,可以参考官网解释:

修改属性值

后来证实,只能改(Tag的)中的属性的值,不能改(Tag的)的值本身

完整示例代码为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【教程】Python中第三方的用于解析HTML的库:BeautifulSoup
 
 
Author:     Crifan Li
Version:    2013-02-01
Contact:    admin at crifan dot com
"""
 
from BeautifulSoup import BeautifulSoup;
 
def beautifulsoupDemo():
    demoHtml = """
<html>
<body>
<div class="icon_col">
        <h1 class="h1user">crifan</h1>
 </div>
 </body>
</html>
""";
    soup = BeautifulSoup(demoHtml);
    print "type(soup)=",type(soup); #type(soup)= <type 'instance'>
    print "soup=",soup;
     
    print '{0:=^80}'.format(" 1. extract content ");
    # method 1: no designate para name
    #h1userSoup = soup.find("h1", {"class":"h1user"});
    # method 2: use para name
    h1userSoup = soup.find(name="h1", attrs={"class":"h1user"});
    # more can found at:
    #http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html#find%28name,%20attrs,%20recursive,%20text,%20**kwargs%29
    print "h1userSoup=",h1userSoup; #h1userSoup= <h1 class="h1user">crifan</h1>
    h1userUnicodeStr = h1userSoup.string;
    print "h1userUnicodeStr=",h1userUnicodeStr; #h1userUnicodeStr= crifan
     
    print '{0:=^80}'.format(" 2. demo change tag value and property ");
    print '{0:-^80}'.format(" 2.1 can NOT change tag value ");
    print "old tag value=",soup.body.div.h1.string; #old tag value= crifan
    changedToString = u"CrifanLi";
    soup.body.div.h1.string = changedToString;
    print "changed tag value=",soup.body.div.h1.string; #changed tag value= CrifanLi
    print "After changed tag value, new h1=",soup.body.div.h1; #After changed tag value, new h1= <h1 class="h1user">crifan</h1>
 
    print '{0:-^80}'.format(" 2.2 can change tag property ");  
    soup.body.div.h1['class'= "newH1User";
    print "changed tag property value=",soup.body.div.h1; #changed tag property value= <h1 class="newH1User">crifan</h1>
 
if __name__ == "__main__":
    beautifulsoupDemo();

总结

更多的,用法和使用心得,部分内容,已整理到:

【总结】Python的第三方库BeautifulSoup的使用心得

【整理】关于Python中的html处理库函数BeautifulSoup使用注意事项

Python中第三方的用于解析HTML的库:BeautifulSoup的更多相关文章

  1. Python中第三方模块requests解析

    一.简述 Requests HTTP Library 二.模块框架 ''' __version__ _internal_utils adapters api auth certs compat coo ...

  2. Python中第三方库Requests库的高级用法详解

    Python中第三方库Requests库的高级用法详解 虽然Python的标准库中urllib2模块已经包含了平常我们使用的大多数功能,但是它的API使用起来让人实在感觉不好.它已经不适合现在的时代, ...

  3. python中format函数用于字符串的格式化

    python中format函数用于字符串的格式化 通过关键字 print('{名字}今天{动作}'.format(名字='陈某某',动作='拍视频'))#通过关键字 grade = {'name' : ...

  4. Python基础【3】:Python中的深浅拷贝解析

    深浅拷贝 在研究Python的深浅拷贝区别前需要先弄清楚以下的一些基础概念: 变量--引用--对象(可变对象,不可变对象) 切片(序列化对象)--拷贝(深拷贝,浅拷贝) 我是铺垫~ 一.[变量--引用 ...

  5. Python中的MRO(方法解析顺序)[转载]

    本文转载至: http://hanjianwei.com/2013/07/25/python-mro/ 对于支持继承的编程语言来说,其方法(属性)可能定义在当前类,也可能来自于基类,所以在方法调用时就 ...

  6. 【转】python中的闭包详细解析

    一.什么是闭包? 如果一个内嵌函数访问外部嵌套函数作用域的变量,并返回这个函数,则这个函数就是闭包 闭包必须满足三个条件: 1. 必须有一个内嵌函数    2. 内嵌函数必须引用外部嵌套函数中的变量  ...

  7. python中函数的参数解析

    python中函数的各种参数梳理: 1.形参:函数定义时传入的参数 2.实参:函数调用时传入的参数 (有形参必传实参,形参里自身特点可不传的,可传可不传) 3.缺省参数:不传为默认值,传了会覆盖(下面 ...

  8. python中if __name__ == '__main__': 解析

    当你打开一个.py文件时,经常会在代码的最下面看到if __name__ ==  '__main__':,现在就来介 绍一下它的作用. 模块是对象,并且所有的模块都有一个内置属性 __name__.一 ...

  9. python中 urllib, urllib2, httplib, httplib2 几个库的区别

    转载 摘要: 只用 python3, 只用 urllib 若只使用python3.X, 下面可以不看了, 记住有个urllib的库就行了 python2.X 有这些库名可用: urllib, urll ...

随机推荐

  1. oracle中创建数据库

    一.在Oracle中创建数据库之前先改一下虚拟机的IP地址,以便访问 2. 3. 3.1 3.2 3.3 3.4 创建完成:输入sqlplus sys/123456 as sysdba测试

  2. VBA在WORD应用中如何确定文本是否被选定

    确定文本是否被选定Selection 对象的 Type 属性返回所选内容类型的信息.如果所选内容为插入点,则下列示例显示一条消息. Sub IsTextSelected()    If Selecti ...

  3. holer实现外网访问内网数据库

    外网访问本地数据库 本地安装了数据库,只能在局域网内访问,怎样从公网也能访问内网数据库? 本文将介绍使用holer实现的具体步骤. 1. 准备工作 1.1 安装并启动数据库 默认安装的数据库端口是33 ...

  4. 树莓派外网ssh访问holer实现篇

    外网ssh访问树莓派 内网的树莓派(Raspberry Pi),只能在局域网内访问,怎样从公网也能ssh登录访问树莓派? 本文将介绍使用holer实现的具体步骤. 1. 准备工作 1.1 安装并启动树 ...

  5. 【原创】ACR傻瓜式破解IC芯片卡

    1.简介: 智能卡(英语:Smart card 或IC Card),又称智慧卡.聪明卡.集成电路卡及IC卡,是指粘贴或嵌有集成电路芯片的一种便携式卡片塑料.卡片包含了微处理器.I/O接口及存储器,提供 ...

  6. shell编程规范:引用

    Shell代码规范 作 者: 毕小朋 用 途: 规范Shell代码书写,方便查看与修改 博 客: http://blog.csdn.net/wirelessqa 参 考: http://www.ohl ...

  7. 读取Excel,单元格内容大于255个字符自动被截取的问题

    DataSet ds = new DataSet(); cl_initPage.v_DeBugLog("ExcelDataSource进入"); string strConn; s ...

  8. C# 延迟函数

    #region 延迟函数 public static bool Delay(int delayTime) { DateTime now = DateTime.Now; int s; do { Time ...

  9. pycharm安装pip报错的处理办法

    这几天在用pycharm的时候,发现安装软件的时候报 module 'pip' has no attribute 'main' ,后来综合网上的办法以及分析错误提示,原因是在于pycharm安装目录下 ...

  10. 两种语言实现设计模式(C++和Java)(四:适配器模式)

    参考:http://blog.jobbole.com/109381/ 将一个类的接口转换成客户希望的另外一个接口.Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作. 系统的数 ...