BeautifulSoup的基本使用

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

参考资料:
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])
### BeautifulSoup 基本语法和常用操作 #### 初始化BeautifulSoup对象 为了使用BeautifulSoup处理HTML或XML文档,首先需要创建一个`BeautifulSoup`实例。这通常涉及到读入一段字符串形式的HTML内容并指定解析器。 ```python from bs4 import BeautifulSoup 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> """ soup = BeautifulSoup(html_doc, 'lxml') ``` 这段代码展示了如何初始化一个`BeautifulSoup`对象,并指定了'lxml'作为解析库[^1]。 #### 查找单个标签 可以利用`.find()`方法来定位第一个匹配到的标签;如果想要获取特定名称的第一个标签,则可以直接调用该标签名作为属性访问。 ```python first_paragraph = soup.p # 获取第一个<p>标签 print(first_paragraph) specific_tag = soup.find('a', {'id': 'link2'}) # 使用字典参数查找具有特定ID的<a>标签 print(specific_tag) ``` #### 遍历子节点与父节点 对于已找到的元素,可以通过`.children`, `.descendants`, 或者`.parent`等属性轻松地遍历其后代或祖先节点。 ```python for child in first_paragraph.children: print(child) ancestor = specific_tag.parent.name # 找到链接所在段落的名字 print(f"The parent tag name is {ancestor}") ``` #### CSS选择器支持 除了传统的基于树结构的方法外,还可以借助CSS选择器来进行更灵活的选择。比如,要选出所有的<li>项: ```python all_li_elements = soup.select('li') # 返回列表中的所有<li>元素 print(all_li_elements) ``` 另外,也能够实现复杂的组合查询,像上面提到的例子那样,在多个层次间进行筛选[^3]。 #### 提取文本和其他属性 当找到了目标标签之后,往往还需要进一步提取其中的文字或其他特性值。这时就可以分别运用`.get_text()`, `string` 属性以及通过方括号索引来取得自定义属性的内容。 ```python text_content = all_li_elements[0].get_text() attribute_value = specific_tag['href'] print(text_content, attribute_value) ``` 以上就是关于BeautifulSoup的一些基础功能介绍及其基本的操作方式[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值