关于BeautifulSoup的基础知识
一、BeautifulSoup是什么?
简单来说,Beautiful Soup 是 python 的一个库,最主要的功能是从网页抓取数据。
Beautiful Soup 提供一些简单的、python 式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据, Beautiful Soup 自动将输入文档转换为 Unicode 编码,输出文档转换为 utf-8 编码,Beautiful Soup 已成为和 lxml、html6lib 一样出色的 python 解释器
二、安装
1.安装库
pip install BeautifulSoup
2.Beautiful Soup解析器
BeautifulSoup支持python标准库中的HTML解释器,
lxml解释器比较强大,推荐使用
3.Beautiful Soup创建对象
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>
</body>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
4.四大对象种类
Beautiful Soup 将复杂 HTML 文档转换成一个复杂的树形结构,每个节点都是 Python 对象,所有对象可以归纳为 4 种:
Tag NavigableString BeautifulSoup Comment
在Python 中通过type检查类型
(1)获取标签
print(soup.title)
#<title>The Dormouse's story</title>
(2)soup.select_one()与soup.select() 返回的是列表
通过标签名的查找
print(soup.select_one('p'))
#<p class="title" name="dromouse"><b>The Dormouse's story</b></p>print(soup.select('a'))
print(soup.select('p'))
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
通过类名去查找
print(soup.select(.title))
# [<p class="title" name="dromouse"><b>The Dormouse's story</b></p>]
5.对象是Comment,爬取页面的时候获取到注释部分
删除注释
代码如下
for element in soup(text=lambda text: isinstance(text, (bs4.element.Comment, bs4.element.ProcessingInstruction))):
element.extract()