Python爬虫包BeautifulSoup简介与安装

Chloe
Chloe
发布时间:2026-10-12 | 3人浏览过
原创

本文介绍Python爬虫库Beautiful Soup的功能与安装方法。作为网页数据抓取工具,它提供简单的Python式函数处理导航、搜索、修改分析树。文章详细说明了从conda、pip到手动安装的多种途径,并演示了如何创建Beautiful Soup对象及解析HTML内容。

Beautiful Soup 简介

Beautiful Soup 是 Python 的一个库,主要功能是从网页抓取数据。它提供简单的 Python 式函数,用于处理导航、搜索、修改分析树。该库会自动将输入文档转换为 Unicode 编码,并将输出文档转换为 utf-8 编码。如果文档未指定编码,需要手动说明原始编码方式。Beautiful Soup 与 lxml、html6lib 同为 Python 解释器,推荐在项目中使用 Beautiful Soup 4 (BS4)。导入 BS4 时需使用 import bs4。

安装方法

示例使用的版本为 Beautiful Soup 4.3.2,示例源代码使用 Python 3,但作者使用 Python 2.7。已安装 anaconda 的读者可直接使用 pip 安装。conda 搜索后直接安装可能失败,最新版本的安装方法为下载安装包手动安装。示例中安装的版本为 beautifulsoup4 (4.5.1)。手动安装 lxml 时,conda 会自动安装依赖包。

anaconda search -t conda beautifulsoup
conda install beautifulsoup4
pip install beautifulsoup4
sudo python setup.py install
pip install lxml

创建与使用对象

创建 Beautiful Soup 对象需首先导入 bs4 库。可用 urlopen 读取 HTML 内容并创建对象,也可用本地 HTML 文件来创建 Beautiful Soup 对象。格式化打印输出解析后的 HTML 层次结构。

from bs4 import BeautifulSoup
import sys
if sys.version_info[0] == 2:
  from urllib2 import urlopen # Python 2
else:
  from urllib.request import urlopen # Python3

html = urlopen(http://www.pythonscraping.com/exercises/exercise1.html)
bsObj = BeautifulSoup(html.read())
print(bsObj.h1)
soup = BeautifulSoup(open('index.html'))
print bsObj.h1
print bsObj.prettify()
<html>
 <head>
 <title>
  A Useful Page
 </title>
 </head>
 <body>
 <h1>
  An Interesting Title
 </h1>
 <div>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaec cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
 </div>
 </body>
</html>

以上就是Python爬虫包BeautifulSoup简介与安装的详细内容,更多关于Python爬虫的资料请关注本站其它相关文章!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表