bs4 库

bs4库简介

BeautifulSoup库是解析、遍历、维护标签树代码的功能库;名字为beautifulsoup4,简称bs4

安装方法

pip install beautifulsoup4

使用方法

导包

from bs4 import BeautifulSoup

获取内容或文件

html = BeautifulSoup(test, 'html.parser') #获取网页内容

获取html标签属性及文本

语法

	某某.p 	#获取html下的第一个p标签
	某某.body.div.a	#顺着节点找到a标签
	某某.p.parent.name #找p标签的父元素标签
	某某.find_all('p') #获取html下的所有p标签
	某某.find(class='p1') #获取class为p1的标签

实例

from bs4 import BeautifulSoup #导包

#网页内容
test = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Study</title>
</head>
<body>
    <div>
        <a>taopai</a>
    </div>
	<h1>java</h1>
	<p href="https://blog.csdn.net/qq_41220451" id="p1">python</p>
	<p href="https://blog.csdn.net/qq_41220451">c</p>
	<a>c++</a>
	<a>html</a>
	<a>html</a>
	<a>css</a>
</body>
</html>
"""
#获取网页内容
html = BeautifulSoup(test, 'html.parser')  

获取html下的第一个p标签

p = html.p
print(p)

结果:<p class="p1" href="https://blog.csdn.net/qq_41220451">python</p>

找p标签的父元素标签

p = html.p.parent.name
print(p)

结果:body

顺着节点找到a标签

#顺着节点找到a标签
a = html.body.div.a
print(a)

结果:<a>taopai</a>s

获取第一个p标签中的class属性值

p = html.p['class']
print()

结果:['p1']

获取html下所有p标签

p = html.find_all('p')
print(p)

结果:[<p class="p1" href="https://blog.csdn.net/qq_41220451">python</p>, <p href="https://blog.csdn.net/qq_41220451">c</p>]

获取id为p1的标签

p = html.find(id='p1') 
print(p)

结果:<p href="https://blog.csdn.net/qq_41220451" id="p1">python</p>

强调一下find 和 find_all 可以有多个搜索条件叠加,比如

find('p', id='p1', class_='pp')
class使用时需要加上下横杠,因为class在python中也存在

如有错误,请指正

@taopad

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值