BeautifulSoup
是一个高效的网页解析库,可以从HTML或XML文件中提取数据
支持不同的解析器,比如,对HTML解析,对XML解析,对HTML5解析
就是一个非常强大的工具,爬虫利器
一个灵感又方便的网页解析库,处理高效,支持多种解析器
利用它就不用编写正则表达式也能方便的实现网页信息的抓取
解析库
解析器 | 使用方法 | 优势 | 劣势 |
---|---|---|---|
Python标准库 | BeautifulSoup(markup, “html.parser”) | Python的内置标准库、执行速度适中 、文档容错能力强 | Python 2.7.3 or 3.2.2)前的版本中文容错能力差 |
lxml HTML 解析器 | BeautifulSoup(markup, “lxml”) | 速度快、文档容错能力强 | 需要安装C语言库 |
lxml XML 解析器 | BeautifulSoup(markup, “xml”) | 速度快、唯一支持XML的解析器 | 需要安装C语言库 |
html5lib | BeautifulSoup(markup, “html5lib”) | 最好的容错性、以浏览器的方式解析文档、生成HTML5格式的文档 | 速度慢、不依赖外部扩展 |
安装
pip install BeautifulSoup4
Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库
pip install lxml
lxml 是一种使用 Python 编写的解析库,可以迅速、灵活地处理 XML 和 HTML
基本使用
标签选择器,通过标签选择
.标签 --获取标签内容(第一个,下面除了find_all都是返回第一个)
获取文本内容
.string --获取文本内容
获取名称
.name --获取标签本身名称
获取属性的值
.attrs[] --通过属性拿属性的值
find_all(),find用法相同,但只返回第一个
使用find_all()根据标签名查找
get_text() 获取内容
使用find_all()根据属性查找
text=() 根据文本值选择
例子
h = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class="title" name="dromouse"><b><span>The Dormouse's story</span></b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(h,