BeautifulSoup是一个可以从HTML或者XML文件中提取数据的Python库,它通过解析器把文档解析为利于人们理解的文档导航模式,有利于查找和修改文档。

BeautifulSoup3目前已经停止开发,现在推荐使用BeautifulSoup4,它被移植到了bs4中。

  1. # 使用时需要导入
  2. from bs4 import BeautifulSoup

解析器

BeautifulSoup4中常用4种主要的解析器,使用前需要安装:

  1. #不同系统安装方法
  2. $ apt-get install Python-lxml
  3. $ easy_install lxml
  4. $ pip install lxml
  5.  
  6. # pycharm中安装可以先import xxx,显示有错误然后点击安装,安装后删除import语句,即可正常使用
解析器的优缺点对比
解析器 使用方法 优势 劣势
Python标准库

BeautifulSoup(DocumentName, "html.parser")

  • Python的内置标准库
  • 不需要单独安装
  • 执行速度适中
  • 文档容错能力强
Python 2.7.3 or 3.2.2前的班中文容错能力差
lxml HTML解析器 BeautifulSoup(DocumentName, "lxml")
  • 速度快
  • 文档容错能力强
需要安装C语言库
lxml XML解析器

BeautifulSoup(DocumentName, "xml")

BeautifulSoup(DocumentName, ["lxml","xml"])

  • 速度快
  • 唯一支持XML的解析器
需要安装C语言库
html5lib BeautifulSoup(DocumentName, "html5lib")
  • 最好的容错
  • 以浏览器的方式解析文档
  • 生成HTML5格式的文档
速度慢,需要依赖python库

不同解析器的解析结果:

  1. # 符合HTML标准的解析结果
    htmldoc = "<a><p></p></a>"
  2. print("None :",BeautifulSoup(htmldoc))
  3. print("html.parser :", BeautifulSoup(htmldoc, "html.parser"))
  4. print("lxml :", BeautifulSoup(htmldoc, "lxml"))
  5. print("xml :", BeautifulSoup(htmldoc, "lxml-xml"))
  6. print("html5lib :", BeautifulSoup(htmldoc, "html5lib"))
  7.  
  8. """
  9. 结果为:
  10. None : <html><body><a><p></p></a></body></html>
  11. html.parser : <a><p></p></a>
  12. lxml : <html><body><a><p></p></a></body></html>
  13. xml : <?xml version="1.0" encoding="utf-8"?>
  14.   <a><p/></a>
  15. html5lib : <html><head></head><body><a><p></p></a></body></html>
  16. """
  1. # 不符合HTML标准的解析结果
  2. htmldoc = "<a></p></a>"
  3. print("None :",BeautifulSoup(htmldoc))
  4. print("html.parser :", BeautifulSoup(htmldoc, "html.parser"))
  5. print("lxml :", BeautifulSoup(htmldoc, "lxml"))
  6. print("xml :", BeautifulSoup(htmldoc, "lxml-xml"))
  7. print("html5lib :", BeautifulSoup(htmldoc, "html5lib"))
  8.  
  9. """
  10. 结果为:
  11. None : <html><body><a></a></body></html>
  12. html.parser : <a></a>
  13. lxml : <html><body><a></a></body></html>
  14. xml : <?xml version="1.0" encoding="utf-8"?>
  15.           <a/>
  16. html5lib : <html><head></head><body><a><p></p></a></body></html>
  17. """

html5lib会把所有的标签不全,并且加上html、head、body,标准的html格式;默认、html.parser、lxml 解析器会把错误标签忽略掉。

编码

任何HTML或者XML文档都有自己的编码方式,但使用BeautifulSoup解析后,文档都会被转换为Unicode,输出时编码均为UTF-8。

因为BeautifulSoup用来编码自动检测库来识别当前文档的编码,并自动转换为Unicode编码。但也有小概率会识别出错,可以用.original_encoding来检测编码格式。

并且设置from_encoding参数可以提高文档的解析速度。

  1. htmldoc = b"<h1>\xed\xe5\xec\xf9</h1>"
  2. soup = BeautifulSoup(htmldoc, from_encoding="iso-8859-8")
  3. print(soup.h1)
  4. print(soup.original_encoding)
  5.  
  6. """
  7. 结果:
  8. <h1>םולש</h1>
  9. 'iso8859-8'
  10. """

指定输出编码:

  1.  
  1. htmldoc = b"<h1>\xed\xe5\xec\xf9</h1>"
  2. soup = BeautifulSoup(htmldoc, from_encoding="iso-8859-8")
    print(soup.prettify("latin-1"))
  1. """
    结果:
    b'<h1>\n νεμω\n</h1>'
  2. """

遍历文档树:

1. 注释<class 'bs4.element.Comment'> 和 替换Comment内容

  1. htmldoc = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
  2. soup = BeautifulSoup(htmldoc)
  3. comment = soup.b.string
  4. print(comment)
  5. print(type(comment))
  6. print(soup2.b)
  7. print(soup2.b.prettify()) #comment特色输出方式
  8.  
  9. # 替换Comment
  10. cdata= CData("A CData block")
  11. comment.replace_with(cdata)
  12. print(soup2.b.prettify())
  13.  
  14. """
  15. 结果:
  16. Hey, buddy. Want to buy a used parser?
  17. <class 'bs4.element.Comment'>
  18. <b><!--Hey, buddy. Want to buy a used parser?--></b>
  19. <b>
  20. <!--Hey, buddy. Want to buy a used parser?-->
  21. </b>
  22. <b>
  23. <![CDATA[A CData block]]>
  24. </b>
  25. """

CData使用时需要导入 from bs4 import CData

2. soup.tagName  返回类型 <class 'bs4.element.Tag'>,得到文档中第一个tagName标签 ==  soup.find(tagName)

  1. soup.div #得到文章中第一个div标签
  2. soup.a #得到文章中第一个a标签

3. soup.tagName.get_text() / soup.tagName.text 返回类型 <class 'str'>,得到该标签内容,对每个BeautifulSoup处理后的对象都生效。

  1. soup.a.get_text()
  2. soup.a.text

4. soup.tagName.tagName["AttributeName"] 获得标签内属性值,逐级访问标签可以用 . 连接,某个属性值用 ["属性名"] 访问。

  1. soup.div.a['href']

5. soup.ul.contents 返回类型为<class 'list'>,可以用下标访问其中的元素

 list内元素类型为 <class 'bs4.element.Tag'> or <class 'bs4.element.NavigableString'>

 如果是单一标签可以用 string 返回文本,如果超过1个标签就返回None

  1. soup.ul.contents
  2. type(soup.ul.contents) #<class 'list'>
  3. soup.ul.contents[0].string
  4. type(soup.ul.contents[0])

6. find_all(name, attrs, recursice, text, limit, **kwargs),返回的类型为 <class 'bs4.element.ResultSet'>

  1. # 找到所有标签为tagName的集合
  2. soup.find_all("tagName")
  3. soup.find_all("a")
  4.  
  5. # 找到所有标签为tagName 且 class=className的集合
  6. soup.find_all("tagName", "className")
  7. soup.find_all("div","Score")
  8.  
  9. # 找到所有id=idName的标签
  10. soup.find_all(id = "idName")
  11.  
  12. # 使用多个指定名字的参数可以同时过滤tag的多个属性:
  13. soup.find_all(href = re.compile("else"))
  14. soup.find_all(href=re.compile("elsie"), id='link1')
  15. # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
  16.  
  17. # 有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性
  18. data_soup = BeautifulSoup('<div data-foo="value">foo!</div>')
  19. data_soup.find_all(data-foo="value")
  20. # SyntaxError: keyword can't be an expression
  21. # 可以用attrs 参数定义一个字典参数来搜索包含特殊属性的tag
  22. data_soup.find_all(attrs={"data-foo": "value"})
  23. # [<div data-foo="value">foo!</div>]
  24.  
  25. # 找到所有有id的标签
  26. soup.find_all(id = True)
  27.  
  28. # 找到所有标签为tagName且class = "className"的标签
  29. soup.find_all("tagName", class_ = "className")
  30. # css class参数过滤
  31. soup.find_all(class_=re.compile("itl"))
  32. # [<p class="title"><b>The Dormouse's story</b></p>]
  33.  
  34. # 通过文本查找文本
  35. soup.find_all(text = "textContent")
  36. soup.find_all(text = ["Content1", "Content2"])
  37. # 文本参数过滤
  38. soup.find_all(text=re.compile("Dormouse"))
  39.  
  40. # 限制结果个数
  41. soup.find_all("tagName", limit = 2)
  42. elemSet = soup.find_all("div", limit = 2)
  43. # 可循环出每个元素
  44. for item in elemSet:
  45. print(item)
  46. print(item.text)

7. 通过 css 选择器查找,返回值 <class 'list'>,list中元素类型为 <class 'bs4.element.Tag'>

  1. htmldoc = """
  2. <html><head><title>The Dormouse's story</title></head>
  3. <p class="title"><b>The Dormouse's story</b></p>
  4. <p class="story">Once upon a time there were three little sisters; and their names were
  5. <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
  6. <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
  7. <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
  8. and they lived at the bottom of a well.</p>
  9. <p class="story">...</p>
  10. """
  11. soup = BeautifulSoup(htmldoc, "lxml")
  12.  
  13. # tag标签查找
  14. soup.select("title")
  15.  
  16. # tag标签逐层查找
  17. soup.select("html head title")
  18. soup.select("head title")
  19. soup.select("body a")
  20.  
  21. # tag标签下的直接子标签
  22. soup.select("head > title")
  23. soup.select("p > a")
  24. soup.select("p > a:nth-of-type(2)")
  25. soup.select("p > #link1")
  26.  
  27. # css类名查找
  28. soup.select(".sister")
  29.  
  30. # id 查找
  31. soup.select("#link1")
  32.  
  33. # 通过属性查找
  34. soup.select("a[href]")
  35. soup.select('a[href="http://example.com/elsie"]')
  36. soup.select('a[href^="http://example.com/"]')
  37. soup.select('a[href$="tillie"]')
  38. soup.select('a[href*=".com/el"]')
  39. type(soup.select("a[href]")) # <class 'list'>
  40.  
  41. # 通过循环获取到每个tag
  42. list = soup.select("a[href]")
  43. for item in list:
  44. print(item)
  45. print(type(item)) # <class 'bs4.element.Tag'>
  46. print(item.text)
  47. print(item.string)

Python BeautifulSoup库的用法的更多相关文章

  1. python BeautifulSoup库用法总结

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

  2. PYTHON 爬虫笔记五:BeautifulSoup库基础用法

    知识点一:BeautifulSoup库详解及其基本使用方法 什么是BeautifulSoup 灵活又方便的网页解析库,处理高效,支持多种解析器.利用它不用编写正则表达式即可方便实现网页信息的提取库. ...

  3. python BeautifulSoup库的基本使用

    Beautiful Soup 是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree). 它提供简单又常用的导航(navigating),搜索以 ...

  4. python 时间库的用法 时区的转化

    1. 月份的加减 https://blog.csdn.net/qq_18863573/article/details/79444094 第三方模块:python-dateutil import dat ...

  5. python requests库的用法

    参考  http://docs.python-requests.org/zh_CN/latest/user/quickstart.html 1.传递url参数 >>> payload ...

  6. Python爬虫-- BeautifulSoup库

    BeautifulSoup库 beautifulsoup就是一个非常强大的工具,爬虫利器.一个灵活又方便的网页解析库,处理高效,支持多种解析器.利用它就不用编写正则表达式也能方便的实现网页信息的抓取 ...

  7. Python HTTP库requests中文页面乱码解决方案!

    http://www.cnblogs.com/bitpeng/p/4748872.html Python中文乱码,是一个很大的坑,自己不知道在这里遇到多少问题了.还好通过自己不断的总结,现在遇到乱码的 ...

  8. $python爬虫系列(2)—— requests和BeautifulSoup库的基本用法

    本文主要介绍python爬虫的两大利器:requests和BeautifulSoup库的基本用法. 1. 安装requests和BeautifulSoup库 可以通过3种方式安装: easy_inst ...

  9. Python爬虫小白入门(三)BeautifulSoup库

    # 一.前言 *** 上一篇演示了如何使用requests模块向网站发送http请求,获取到网页的HTML数据.这篇来演示如何使用BeautifulSoup模块来从HTML文本中提取我们想要的数据. ...

随机推荐

  1. Visual Studio 2010调试本地 IIS 站点

    点击vs的Debug-Attach to Process选中 w3wp.exe,然后点击Attach, vs便进入debug模式.

  2. js实现选项卡切换

    <!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...

  3. js实现在表格中删除和添加一行

    <!DOCTYPE html><html> <head> <title> new document </title> <meta ht ...

  4. mvc全局过滤器和httpmodule的执行顺序

    根据http管线模型,请求先通过httpmodule,再通过httphandler,之后再进入mvc的过滤器 另外参考:MVC如何在Pipeline中接管请求的? http://www.cnblogs ...

  5. URLRewrite 实现方法详解

    所谓的伪静态页面,就是指的URL重写,在ASP.NET中实现非常简单首先你要在你的项目里引用两个DLL:ActionlessForm.dll.URLRewriter.dll,真正实现重写的是 URLR ...

  6. 表单使用clone方法后, 原有select无法生效

    textarea和select的值clone的时候会丢掉,在clone的时候将val再重新赋值一下,如果知道这个了就加单了   测试发现,textarea和select的jquery的clone方法有 ...

  7. C#中的枚举使用

    基本用法 默认从0开始分配各个枚举值对应的数字值 public enum VariableType { Type1, Type2 } 指定各个枚举值对应的数字值 public enum Variabl ...

  8. whisper简介

    以太坊系列之二十 以太坊中的基础应用whisper 以太坊系列之二十 以太坊中的基础应用whisper 1 whisper介绍 2 whisper rpc模块 3 whisper中的消息 4 消息的加 ...

  9. day02.1-字符串内置方法

    字符串——str的定义:test = "zizaijiapu" 特点:1. 字符串是可迭代对象: 2. 字符串中各元素是有序的: 3. 字符串一经创建,其内容值不可修改. 1. 查 ...

  10. vs引入资源

    把资源放在程序目录中,然后点击显示所有文件,然后在资源上右键“包括在项目中”