BeautifulSoup的基本使用

本文详细介绍了如何使用BeautifulSoup库解析HTML文档,包括基本标签操作、内容查找、正则表达式搜索、函数驱动搜索、CSS选择器的应用,并展示了如何通过CSS选择器找到并处理特定类和ID的元素。

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

参考资料:
B站:beautifulSoup

import bs4
from bs4 import BeautifulSoup
file= open(r"C:\Users\lord\Desktop\b.html","rb")
# html=file.read().decode("utf-8")
html=file.read()

bs=BeautifulSoup(html,"html.parser")##parser解析器

#1.Tag 标签及其内容:拿到它所找到的第一个内容
# print(bs.title)
# print(bs.a)
# print(bs.head)
# print(type(bs.title))
# print(bs.title.string)
#NavigableString 标签里的内容
# print(type(bs.title.string))
# print(bs.a.attrs)
# print(type(bs))#class 'bs4.BeautifulSoup'表示整个文档
# print(bs)
#comment 是一个特殊的NavigableString,输出的内容不包含注释符号
#应用:
# #文档的遍历
# print(bs.head.contents)
# print((bs.head.contents)[1])
##遍历文件树,自行百度

##文档的搜索
#(1)find_all()
# 字符串过渡:会查找与字符串完全匹配的内容
# t_list=bs.find_all("a")
# print(t_list)
# (2)正则表达式;使用search()方法来匹配内容
import re
# t_list=bs.find_all(re.compile("a"))
# print(t_list)
#(3)方法:传入一个函数(方法),根据函数的要求来搜索
# def name_is_exists(tag):
#     return tag.has_attr("name")
# 
# t_list=bs.find_all(name_is_exists)
# 
# print(t_list)
#2.kwargs 参数
# t_list=bs.find_all(id="head")
# # t_list=bs.find_all(class=True)
# for item in t_list:
#     print(item)
# 3.text参数
# t_list=bs.find_all(text="hao123")
# # for item in t_list:
# #     print(item)
# t_list=bs.find_all(text=re.compile("\d"))#应用正则表达式来查找包含特定文本的内容(标签里的字符串)#\d 匹配数字
# for item in t_list:
#     print(item)
#4.limt 参数
# t_list=bs.find_all("a",limit=3)
#css选择器
# print(bs.select('title'))#通过标签来查找
# print(bs.select('.mnav'))#通过类名查找
# print(bs.select('#u1'))#通过id来查找
# print(bs.select('a[class="bri"]'))#通过属性来查找
# print(bs.select('head>title'))#通过子标签来查找
t_list = bs.select(".mnav ~ .bri")
# print(t_list[0].get_text())
print(t_list[0])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值