【Python3 爬虫】U10_初识BeautifulSoup4库

1.简介

和 lxml 一样,Beautiful Soup 也是一个HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 数据。lxml 只会局部遍历,而Beautiful Soup 是基于HTML DOM的,会载入整个文档,解析整个DOM树,因此时间和内存开销都会大很多,所以性能要低于lxml。
BeautifulSoup 用来解析 HTML 比较简单,API非常人性化,支持CSS选择器、Python标准库中的HTML解析器,也支持 lxml 的 XML解析器。
Beautiful Soup 3 目前已经停止开发,推荐现在的项目使用Beautiful Soup 4。

2.安装

pip install beautifulsoup4

中文文档:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

3.几大解析工具对比

解析工具 解析速度 使用难度
Beautiful Soup 最慢 最简单
lxml 简单
正则 最快 最难

4.BeautifulSoup库的基本使用

from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</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>
"""

# 创建BeautifulSoup对象,并使用lxml解析
soup = BeautifulSoup(html,'lxml')
print(soup.prettify())

输出结果如下:

原文地址:https://www.cnblogs.com/OliverQin/p/12594467.html