21. BeautifulSoup4

1. bs4简介

1.1 基本概念

  • BeautifulSoup4 简称 bs4, 是一个可以从HTML或xml文件中提取数据的网页信息提取库

1.2 源码分析

  • github下载源码
  • 安装:pip install lxml pip install bs4

2. bs4的使用

2.1 快速开始

html_doc="""
<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>
</html>
"""
# 获取bs4对象
bs = BeauifulSoup(html_doc,'lxml')
# 打印文档内容,更加规范的打印
print(bs.prettify())
print(bs.title)
print(bs.title.name)
print(bs.title.string)
print(bs.p)

2.2 bs4的对象种类

  • tag :标签
  • NavigableString :可导航的字符串
  • BeaytifulSoup :bs4对象
  • Comment :注释

3. 遍历树 遍历子节点

bs4里面有三种情况:遍历,查找,修改

3.1 contents children descendants

  • contents 返回一个列表
  • children 返回一个迭代器,通过迭代器可以迭代
  • descendants 返回的是一个生成器遍历子子孙孙

3.2 .string .strings .stripped srtings

  • string 获取标签里的内容
  • strings 返回一个生成器对象用来获取多个标签内容
  • stripped srtings 和 strings基本一致,但是可以把多余的空格去掉

4. 遍历树, 遍历父节点

parent和parents

  • parent获取直接父节点
  • parents获取所有的父节点

5. 遍历树 遍历兄弟节点

  • next_sibling sibling 下一个兄弟节点
  • previous_sibling 上一个兄弟节点
  • next_siblings 下一个所有兄弟节点
  • previous_siblings 上一个所有兄弟节点

6. 搜索树

  • 字符串过滤器
  • 正则表达式过滤器:我们⽤正则表达式⾥⾯compile⽅法编译⼀个正则表达式传给 find 或者findall这个⽅法可以实现⼀个正则表达式的⼀个过滤器的搜索
  • 列表过滤器
  • True过滤器
  • 方法过滤器

7. find() 和 find_all()

7.1 find_all()

  • find_all() 以列表形式返回所有搜索到的标签数据
  • find() 方法返回搜索到的第一条数据
  • find_all() 方法参数
def find_all(self, name=None, attrs={}, recursive=True, text=None,limit=None, **kwargs):
	pass
  • name:tag名称
  • attr:标签属性
  • recursive:是否按正常递归搜索,默认值为True
  • text:文本内容
  • limit:限制返回数量
  • kwargs:关键字参数

7.2 find_parents() find_parent() find_nextsibling() find_next_sibling()

  • find_parents : 搜索所有父节点
  • find_parent : 搜索单个父节点
  • find_next_siblings : 搜索所有兄弟节点
  • find_next_sibling : 搜索单个兄弟节点

7.3 搜索与查找

  • find_previous_siblings() 向上搜索所有兄弟节点
  • find_previous_sibling() 向上搜索单个兄弟节点
  • find_all_next() 向下搜索所有元素
  • find_next() 向下查找单个元素

8. 修改文档树

  • 修改tag属性和名称
  • 修改string 属性赋值,相当于用当前的元素代替了原来的内容
  • append() 像tag中添加内容,好像python 列表的.append方法
  • decompose() 删除段落,对于一些没有必要的文章段落的删除操作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值