beautifulsoup的应用

本文介绍BeautifulSoup库的使用方法,包括标准选择器和CSS选择器的运用,演示了如何解析HTML文档,查找特定标签、属性及文本内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
'''
soup = BeautifulSoup(html)

使用BeautifulSoup解析这段代码,能够得到一个 BeautifulSoup 的对象,并能按照标准的缩进格式的结构输出。
1标准选择器
find_all
find_all(name,attrs,recursive,text,**kwargs)可以根据标签名,属性,内容查找文档

find
find(name,attrs,recursive,text,**kwargs)
find返回的匹配结果的第一个元素

结果返回的是一个列表的方式
soup.find_all(text=‘xx’)查询text=xx的文本
attrs可以传入字典的方式来查找标签,但是这里有个特殊的就是class,因为class在python中是特殊的字段,所以如果想要查找class相关的可以更改attrs={‘class_’:‘element’}或者soup.find_all(’’,{“class”:"element}),id等特殊的标签属性可以不写attrs。

2CSS选择器
通过select()直接传入CSS选择器就可以完成选择
[attr] 可以通过这种方法找到具有某个属性的所有标签
[atrr=xx] 例子[target=_blank]表示查找所有target=_blank的标签
get_text()可以获取文本内容
attrs获取属性

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值