Python使用BeautifulSoup库解析HTML基本使用教程


Posted in Python onMarch 31, 2016

 BeautifulSoup是Python的一个第三方库,可用于帮助解析html/XML等内容,以抓取特定的网页信息。目前最新的是v4版本,这里主要总结一下我使用的v3版本解析html的一些常用方法。

准备

1.Beautiful Soup安装

为了能够对页面中的内容进行解析,本文使用Beautiful Soup。当然,本文的例子需求较简单,完全可以使用分析字符串的方式。

执行

sudo easy_install beautifulsoup4

即可安装。

2.requests模块的安装

requests模块用于加载要请求的web页面。

在python的命令行中输入import requests,报错说明requests模块没有安装。

我这里打算采用easy_install的在线安装方式安装,发现系统中并不存在easy_install命令,输入sudo apt-get install python-setuptools来安装easy_install工具。

执行sudo easy_install requests安装requests模块。

基础

1.初始化
   导入模块

#!/usr/bin/env python
from BeautifulSoup import BeautifulSoup    #process html
#from BeautifulSoup import BeautifulStoneSoup #process xml
#import BeautifulSoup             #all

    创建对象:str初始化,常用urllib2或browser返回的html初始化BeautifulSoup对象。

doc = ['hello',
    '
This is paragraph one of ptyhonclub.org.',
    '
This is paragraph two of pythonclub.org.',
    '']
soup = BeautifulSoup(''.join(doc))

    指定编码:当html为其他类型编码(非utf-8和asc ii),比如GB2312的话,则需要指定相应的字符编码,BeautifulSoup才能正确解析。

htmlCharset = "GB2312"
soup = BeautifulSoup(respHtml, fromEncoding=htmlCharset)

2.获取tag内容
   寻找感兴趣的tag块内容,返回对应tag块的剖析树

head = soup.find('head')
#head = soup.head
#head = soup.contents[0].contents[0]
print head

    返回内容:hello
   说明一下,contents属性是一个列表,里面保存了该剖析树的直接儿子。

html = soup.contents[0]    # <html> ... </html>
head = html.contents[0]    # <head> ... </head>
body = html.contents[1]    # <body> ... </body>

3.获取关系节点
   使用parent获取父节点

body = soup.body
html = body.parent       # html是body的父亲

    使用nextSibling, previousSibling获取前后兄弟

head = body.previousSibling  # head和body在同一层,是body的前一个兄弟
p1 = body.contents[0]     # p1, p2都是body的儿子,我们用contents[0]取得p1
p2 = p1.nextSibling      # p2与p1在同一层,是p1的后一个兄弟, 当然body.content[1]也可得到

    contents[]的灵活运用也可以寻找关系节点,寻找祖先或者子孙可以采用findParent(s), findNextSibling(s), findPreviousSibling(s)

4.find/findAll用法详解
   函数原型:find(name=None, attrs={}, recursive=True, text=None, **kwargs),findAll会返回所有符合要求的结果,并以list返回。
   tag搜索

find(tagname)                 # 直接搜索名为tagname的tag 如:find('head')
find(list)                   # 搜索在list中的tag,如: find(['head', 'body'])
find(dict)                   # 搜索在dict中的tag,如:find({'head':True, 'body':True})
find(re.compile(''))              # 搜索符合正则的tag, 如:find(re.compile('^p')) 搜索以p开头的tag
find(lambda)            # 搜索函数返回结果为true的tag, 如:find(lambda name: if len(name) == 1) 搜索长度为1的tag
find(True)                   # 搜索所有tag

   attrs搜索

find(id='xxx')                 # 寻找id属性为xxx的
find(attrs={id=re.compile('xxx'), algin='xxx'}) # 寻找id属性符合正则且algin属性为xxx的
find(attrs={id=True, algin=None})        # 寻找有id属性但是没有algin属性的


resp1 = soup.findAll('a', attrs = {'href': match1})
resp2 = soup.findAll('h1', attrs = {'class': match2})
resp3 = soup.findAll('img', attrs = {'id': match3})

text搜索
文字的搜索会导致其他搜索给的值如:tag, attrs都失效。方法与搜索tag一致

print p1.text
# u'This is paragraphone.'
print p2.text
# u'This is paragraphtwo.'
# 注意:1,每个tag的text包括了它以及它子孙的text。2,所有text已经被自动转为unicode,如果需要,可以自行转码encode(xxx)

recursive和limit属性
recursive=False表示只搜索直接儿子,否则搜索整个子树,默认为True。当使用findAll或者类似返回list的方法时,limit属性用于限制返回的数量,如findAll('p', limit=2): 返回首先找到的两个tag。

实例
本文以博客的文档列表页面为例,利用python对页面中的文章名进行提取。

文章列表页中的文章列表部分的url如下:

<ul class="listing">
  <li class="listing-item"><span class="date">2014-12-03</span><a href="/post/linux_funtion_advance_feature" title="Linux函数高级特性" >Linux函数高级特性</a>
  </li>
  <li class="listing-item"><span class="date">2014-12-02</span><a href="/post/cgdb" title="cgdb的使用" >cgdb的使用</a>
  </li>
...
</ul>

代码:

#!/usr/bin/env python                                                                              
# -*- coding: utf-8 -*-

' a http parse test programe '

__author__ = 'kuring lv'


import requests
import bs4

archives_url = "http://kuring.me/archive"

def start_parse(url) :
  print "开始获取(%s)内容" % url
  response = requests.get(url)
  print "获取网页内容完毕"

  soup = bs4.BeautifulSoup(response.content.decode("utf-8"))
  #soup = bs4.BeautifulSoup(response.text);

  # 为了防止漏掉调用close方法,这里使用了with语句
  # 写入到文件中的编码为utf-8
  with open('archives.txt', 'w') as f :
    for archive in soup.select("li.listing-item a") :
      f.write(archive.get_text().encode('utf-8') + "\n")
      print archive.get_text().encode('utf-8')

# 当命令行运行该模块时,__name__等于'__main__'
# 其他模块导入该模块时,__name__等于'parse_html'
if __name__ == '__main__' :
  start_parse(archives_url)
Python 相关文章推荐
python通过floor函数舍弃小数位的方法
Mar 17 Python
Django rest framework基本介绍与代码示例
Jan 26 Python
Python3自动签到 定时任务 判断节假日的实例
Nov 13 Python
python使用if语句实现一个猜拳游戏详解
Aug 27 Python
python生成随机红包的实例写法
Sep 02 Python
python实现简易学生信息管理系统
Apr 05 Python
pandas factorize实现将字符串特征转化为数字特征
Dec 19 Python
python对execl 处理操作代码
Jun 22 Python
python文件编写好后如何实践
Jul 07 Python
python 常见的排序算法实现汇总
Aug 21 Python
PyCharm 2020.1版安装破解注册码永久激活(激活到2089年)
Sep 24 Python
教你使用Pandas直接核算Excel中快递费用
May 12 Python
Python使用Mechanize模块编写爬虫的要点解析
Mar 31 #Python
Python语言实现获取主机名根据端口杀死进程
Mar 31 #Python
Linux中Python 环境软件包安装步骤
Mar 31 #Python
Python内置的HTTP协议服务器SimpleHTTPServer使用指南
Mar 30 #Python
横向对比分析Python解析XML的四种方式
Mar 30 #Python
python简单实现刷新智联简历
Mar 30 #Python
详解Python迭代和迭代器
Mar 28 #Python
You might like
PHP下对数组进行排序的函数
2010/08/08 PHP
php INI配置文件的解析实现分析
2011/01/04 PHP
PHP使用DES进行加密与解密的方法详解
2013/06/06 PHP
php的一个简单加密解密代码
2014/01/14 PHP
PHP图片处理之使用imagecopy函数添加图片水印实例
2014/11/19 PHP
javascript实现的网页局布刷新效果
2008/12/01 Javascript
JQuery与JSon实现的无刷新分页代码
2011/09/13 Javascript
jquery获取table中的某行全部td的内容方法
2013/03/08 Javascript
详解AngularJS脏检查机制及$timeout的妙用
2017/06/19 Javascript
vue.js国际化 vue-i18n插件的使用详解
2017/07/07 Javascript
vue组件中的数据传递方法
2018/05/14 Javascript
React注册倒计时功能的实现
2018/09/06 Javascript
如何阻止小程序遮罩层下方图层滚动
2019/09/05 Javascript
浅析JS中NEW的实现原理及重写
2020/02/20 Javascript
JavaScript实现简单贪吃蛇效果
2020/03/09 Javascript
vue实现匀速轮播效果
2020/06/29 Javascript
详解ES6中class的实现原理
2020/10/03 Javascript
[52:15]2014 DOTA2国际邀请赛中国区预选赛5.21 HGT VS LGD-GAMING
2014/05/23 DOTA
[04:07]显微镜下的DOTA2第八期——英雄复活动作
2014/06/24 DOTA
[54:47]Liquid vs VP Supermajor决赛 BO 第五场 6.10
2018/07/05 DOTA
Python入门_学会创建并调用函数的方法
2017/05/16 Python
用Python逐行分析文件方法
2019/01/28 Python
linux环境下Django的安装配置详解
2019/07/22 Python
python字符串格式化方式解析
2019/10/19 Python
pytorch 实现模型不同层设置不同的学习率方式
2020/01/06 Python
如何搭建pytorch环境的方法步骤
2020/05/06 Python
基于python实现操作redis及消息队列
2020/08/27 Python
Python爬虫scrapy框架Cookie池(微博Cookie池)的使用
2021/01/13 Python
西班牙网上书店:Casa del Libro
2016/11/01 全球购物
加拿大在线旅游公司:Flighthub
2019/03/11 全球购物
外企测试工程师面试题
2015/02/01 面试题
升职自荐信范文
2013/10/05 职场文书
关于实现中国梦的心得体会
2016/01/05 职场文书
巧用 -webkit-box-reflect 倒影实现各类动效(小结)
2021/04/22 HTML / CSS
SpringBoot工程下使用OpenFeign的坑及解决
2021/07/02 Java/Android
使用CSS实现音波加载效果
2023/05/07 HTML / CSS