BeautifulSoup的使用

关于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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值