python beautiful soup库的超详细用法

原文地址https://blog.csdn.net/love666666shen/article/details/77512353

参考文章https://cuiqingcai.com/1319.html

1. Beautiful Soup 简介

简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:

Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。

2. Beautiful Soup 安装

Beautiful Soup 3 目前已经停止开发,推荐在现在的项目中使用Beautiful Soup 4,不过它已经被移植到BS4了,也就是说导入时我们需要 import bs4 。所以这里我们用的版本是 Beautiful Soup 4.3.2 (简称BS4),另外据说 BS4 对 Python3 的支持不够好,不过我用的是 Python2.7.7,如果有小伙伴用的是 Python3 版本,可以考虑下载 BS3 版本。

可以利用 pip 或者 easy_install 来安装,以下两种方法均可

  1.  
    easy_install beautifulsoup4
  2.  
    pip install beautifulsoup4

如果想安装最新的版本,请直接下载安装包来手动安装,也是十分方便的方法。下载完成之后解压,运行下面的命令即可完成安装

sudo python setup.py install

然后需要安装 lxml

  1.  
    easy_install lxml
  2.  
    pip install lxml

另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib:

  1.  
    easy_install html5lib
  2.  
    pip install html5lib

Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐安装。

解析器

使用方法

优势

劣势

Python标准库

BeautifulSoup(markup, “html.parser”)

Python的内置标准库

执行速度适中

文档容错能力强

Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差

lxml HTML 解析器

BeautifulSoup(markup, “lxml”)

速度快

文档容错能力强

需要安装C语言库

lxml XML 解析器

BeautifulSoup(markup, [“lxml”, “xml”])

BeautifulSoup(markup, “xml”)

速度快

唯一支持XML的解析器

需要安装C语言库

html5lib

BeautifulSoup(markup, “html5lib”)

最好的容错性

以浏览器的方式解析文档

生成HTML5格式的文档

速度慢

不依

3. 创建 Beautiful Soup 对象

首先必须要导入 bs4 库

from bs4 import BeautifulSoup

我们创建一个字符串,后面的例子我们便会用它来演示

  1.  
    html = """
  2.  
    <html><head><title>The Dormouse's story</title></head>
  3.  
    <body>
  4.  
    <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
  5.  
    <p class="story">Once upon a time there were three little sisters; and their names were
  6.  
    <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
  7.  
    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
  8.  
    <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
  9.  
    and they lived at the bottom of a well. </p>
  10.  
    <p class="story">...</p>
  11.  
    """

创建 beautifulsoup 对象

soup = BeautifulSoup(html)

另外,我们还可以用本地 HTML 文件来创建对象,例如

soup = BeautifulSoup(open('index.html'))

上面这句代码便是将本地 index.html 文件打开,用它来创建 soup 对象。下面我们来打印一下 soup 对象的内容,格式化输出

print soup.prettify()

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

  1.  
    htmlCharset = "GB2312"
  2.  
    soup = BeautifulSoup(respHtml, fromEncoding=htmlCharset)
  1.  
    #!/usr/bin/python
  2.  
    # -*- coding: UTF-8 -*-
  3.  
    from bs4 import BeautifulSoup
  4.  
    import re
  5.  
     
  6.  
    #待分析字符串
  7.  
    html_doc = """
  8.  
    <html>
  9.  
    <head>
  10.  
    <title>The Dormouse's story</title>
  11.  
    </head>
  12.  
    <body>
  13.  
    <p class="title aq">
  14.  
    <b>
  15.  
    The Dormouse's story
  16.  
    </b>
  17.  
    </p>
  18.  
     
  19.  
    <p class="story">Once upon a time there were three little sisters; and their names were
  20.  
    <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
  21.  
    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>
  22.  
    and
  23.  
    <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
  24.  
    and they lived at the bottom of a well.
  25.  
    </p>
  26.  
     
  27.  
    <p class="story">...</p>
  28.  
    """
  29.  
     
  30.  
    # html字符串创建BeautifulSoup对象
  31.  
    soup = BeautifulSoup(html_doc, 'html.parser', from_encoding='utf-8')
  32.  
     
  33.  
    #输出第一个 title 标签
  34.  
    print soup.title
  35.  
     
  36.  
    #输出第一个 title 标签的标签名称
  37.  
    print soup.title.name
  38.  
     
  39.  
    #输出第一个 title 标签的包含内容
  40.  
    print soup.title.string
  41.  
     
  42.  
    #输出第一个 title 标签的父标签的标签名称
  43.  
    print soup.title.parent.name
  44.  
     
  45.  
    #输出第一个 p 标签
  46.  
    print soup.p
  47.  
     
  48.  
    #输出第一个 p 标签的 class 属性内容
  49.  
    print soup.p['class']
  50.  
     
  51.  
    #输出第一个 a 标签的 href 属性内容
  52.  
    print soup.a['href']
  53.  
    '''
  54.  
    soup的属性可以被添加,删除或修改. 再说一次, soup的属性操作方法与字典一样
  55.  
    '''
  56.  
    #修改第一个 a 标签的href属性为 http://www.baidu.com/
  57.  
    soup.a[ 'href'] = 'http://www.baidu.com/'
  58.  
     
  59.  
    #给第一个 a 标签添加 name 属性
  60.  
    soup.a[ 'name'] = u'百度'
  61.  
     
  62.  
    #删除第一个 a 标签的 class 属性为
  63.  
    del soup.a['class']
  64.  
     
  65.  
    ##输出第一个 p 标签的所有子节点
  66.  
    print soup.p.contents
  67.  
     
  68.  
    #输出第一个 a 标签
  69.  
    print soup.a
  70.  
     
  71.  
    #输出所有的 a 标签,以列表形式显示
  72.  
    print soup.find_all('a')
  73.  
     
  74.  
    #输出第一个 id 属性等于 link3 的 a 标签
  75.  
    print soup.find(id="link3")
  76.  
     
  77.  
    #获取所有文字内容
  78.  
    print(soup.get_text())
  79.  
     
  80.  
    #输出第一个 a 标签的所有属性信息
  81.  
    print soup.a.attrs
  82.  
     
  83.  
    for link in soup.find_all('a'):
  84.  
    #获取 link 的 href 属性内容
  85.  
    print(link.get( 'href'))
  86.  
     
  87.  
    #对soup.p的子节点进行循环输出
  88.  
    for child in soup.p.children:
  89.  
    print(child)
  90.  
     
  91.  
    #正则匹配,名字中带有b的标签
  92.  
    for tag in soup.find_all(re.compile("b")):
  93.  
    print(tag.name)
  94.  
     

import bs4#导入BeautifulSoup库
Soup = BeautifulSoup(html)#其中html 可以是字符串,也可以是句柄
需要注意的是,BeautifulSoup会自动检测传入文件的编码格式,然后转化为Unicode格式
通过如上两句话,BS自动把文档生成为如上图中的解析树。


4. 四大对象种类

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:

1. Tag
2. NavigableString
3. BeautifulSoup
4. Comment

猜你喜欢

转载自www.cnblogs.com/111testing/p/10323159.html