python bs4库操作

该代码示例展示了如何使用Python的BeautifulSoup库解析HTML文档,提取<title>标签、<a>标签以及具有特定class属性的<p>标签。它还演示了遍历标签树和获取元素子节点的方法。
摘要由CSDN通过智能技术生成

from bs4 import BeautifulSoup

# find_all or find

doc = '''

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <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 sister;and their names were

    <a href="http://example.com/else" class="sister" id="link1">Elsie</a>

    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>

    <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>

'''

soup = BeautifulSoup(doc, 'lxml')  # 解析html变成beautifulsoup对象

tag = soup.find("title")  # 查找第一个标题标签,title一般只有一个

print(type(tag), tag)  # 显示标签的类型和内容

tag = soup.find("a")  # 查找第一个a标签

print(type(tag), tag)  # 显示标签的类型和内容

tag = soup.find('p', attrs={'class': 'title'}) # 查找文本当中class为title的<p>元素

print(type(tag), tag)  # 显示标签的类型和内容

soup = BeautifulSoup(doc, 'lxml')

print(soup.name)  # 先打印文档名

tag = soup.find('b')

while tag:

    print(tag.name)  # 打印标签名,再进行查找父节点

    tag = tag.parent


 

soup = BeautifulSoup(doc, 'lxml')

print(soup.name)  # 先打印文档名

tag = soup.find('p')

for x in tag.children:  # 获取p元素的所有直接子节点

    print(x)


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值