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

原文地址:https://www.cnblogs.com/111testing/p/10323159.html

时间: 2024-07-31 06:28:24

python beautiful soup库的超详细用法的相关文章

Python网络爬虫与信息提取-Beautiful Soup 库入门

一.Beautiful Soup 库的安装 Win平台:"以管理员身份运行" cmd 执行 pip install beautifulsoup4 安装小测:from bs4 import BeautifulSoup soup=BeautifulSoup('<p>data</p>','html.parser') print(soup.prettify()) 二.Beautiful Soup 库的基本元素 1.BeautifulSoup类 from bs4 impo

Python爬虫学习(二)使用Beautiful Soup库

(一)使用Beautiful Soup库 1,安装Beautiful Soup库:pip install beautifulsoup4 2,简单使用: import requests; from _socket import timeout from bs4 import BeautifulSoup #使用Beautiful Soup库需要导包 #from aifc import data def getHTMLText(url): try: r=requests.get(url,timeout

【Python爬虫学习笔记(2)】Beautiful Soup库相关知识点总结

1. Beautiful Soup简介     Beautiful Soup是将数据从HTML和XML文件中解析出来的一个python库,它能够提供一种符合习惯的方法去遍历搜索和修改解析树,这将大大减少爬虫程序的运行时间.     Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码.你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了.然后,你仅仅需要说明一下原始编码方式就可以了.     B

python之Beautiful Soup库

1.简介 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据.官方解释如下: Beautiful Soup提供一些简单的.python式的函数用来处理导航.搜索.修改分析树等功能.它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序. Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码.你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beaut

python Beautiful Soup的使用

上一节我们介绍了正则表达式,它的内容其实还是蛮多的,如果一个正则匹配稍有差池,那可能程序就处在永久的循环之中,而且有的小伙伴们也对写正则表 达式的写法用得不熟练,没关系,我们还有一个更强大的工具,叫Beautiful Soup,有了它我们可以很方便地提取出HTML或XML标签中的内容,实在是方便,这一节就让我们一起来感受一下Beautiful Soup的强大吧. 1. Beautiful Soup的简介 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据.

推荐一些python Beautiful Soup学习网址

前言:这几天忙着写分析报告,实在没精力去研究django,虽然抽时间去看了几遍中文文档,还是等实际实践后写几篇操作文章吧! 正文:以下是本人前段时间学习bs4库找的一些网址,在学习的可以参考下,有点多,就不啰嗦了! 点击url左侧文字直接进入相关网页 点击url左侧文字直接进入相关网页 点击url左侧文字直接进入相关网页 BeautifulSoup使用总结:http://blog.chinaunix.net/uid-26722078-id-3519422.html Beautiful Soup

python Beautiful Soup 抓取解析网页

Beautiful Soup is a Python library designed for quick turnaround projects like screen-scraping.总之就是一个解析xml和html之类的库,用着还算顺手. 官网地址:http://www.crummy.com/software/BeautifulSoup/ 下面来介绍下使用python和Beautiful Soup 抓取一个网页上的PM2.5数据. PM2.5 数据的网站:http://www.pm25.

Beautiful Soup 库基础知识

1.安装 cmd------->>pip install beautifulsoup4 2.安装测试. import requests # 导入requests库 from bs4 import BeautifulSoup # 导入美味汤库 r = requests.get("http://python123.io/ws/demo.html") print(r.status_code) # 测试是否连接正常 # print(r.text) # 全部文本信息 demo = r

python Beautiful Soup 采集it books pdf,免费下载

http://www.allitebooks.org/ 是我见过最良心的网站,所有书籍免费下载 周末无聊,尝试采集此站所有Pdf书籍. 采用技术 python3.5 Beautiful soup 分享代码 最简单的爬虫,没有考虑太多的容错,建议大家尝试的时候,温柔点,别把这个良心网站搞挂掉了 # www.qingmiaokeji.cn 30 from bs4 import BeautifulSoup import requests import json siteUrl = 'http://ww