本文最后更新于839 天前,其中的信息可能已经过时,如有错误请评论留言
使用BeautifulSoup提取本地HTML文件代码中的内容并按照指定格式输出
曾经很久以前的一个HTML文件,里面有非常多的a标签写的一个网站收录集合,那时候刚学,现在看来写的真的蠢,代码类似下面:
<div id="ITtools" class="">
<h3>IT工具</h3>
<a href="https://www.zaiwen.top/">chatgpt国内免费版</a>
<a href="https://www.gaituya.com/">在线 PS 网站</a>
<a href="https://www.processon.com/">流程思维导图</a>
</div>
<div id="tools" class="">
<h3>工具</h3>
<a href="https://toolwa.com/record/">在线录屏</a>
<a href="https://translate.limit.dev/">GPT翻译</a>
<a href="https://www.deepl.com/translator">deepl最准确翻译</a>
<a href="https://toolwa.com/">工具哇工具合集</a>
</div>
不过其实有非常多,这只是一点,我想把h3和a标签的信息提取出来,就用python写了个程序,想输出的格式为下面这种:
'ACG': [
{ 'name': '可可影视', 'url': 'https://wwnf.lanzouw.com/ikygI1grlryh' },
{ 'name': '二矿动漫', 'url': 'https://www.ntdm9.com/' },
{ 'name': '百万美金主(全是广告)', 'url': 'http://www.milliondollarhomepage.com/' },
{ 'name': '网址库Hanime', 'url': 'https://www.wangzhiku.com/w/5903/' },
{ 'name': '磁力天堂', 'url': 'https://cilitiantang.one/sitetag/skrbt' },
],
'PPT图片设计等工具': [
{ 'name': '哩布哩布生成图', 'url': 'https://www.liblib.ai/sd' },
{ 'name': '做包装设计', 'url': 'https://www.pacdora.cn/' },
{ 'name': 'CS自学指南', 'url': 'https://csdiy.wiki/' },
],
将h3和a标签的信息替换进去
实际实现出来的python代码如下:
from bs4 import BeautifulSoup
path = "C:/Users/31615/Desktop/自用web/全网站收藏夹.html"
# 读取本地HTML文件
with open(path, "r", encoding="utf-8") as f:
html_doc = f.read()
# 创建BeautifulSoup对象
soup = BeautifulSoup(html_doc, "html.parser")
# 查找所有 h3 标题
h3_headers = soup.find_all("h3")
# 遍历每个 h3 标题,并提取其后的链接
results = {}
for h3 in h3_headers:
category = h3.text.strip() # 获取标题文本作为类别
links = h3.find_next_siblings("a") # 获取标题后的所有链接
results[category] = [
{"name": link.text.strip(), "url": link.get("href")} for link in links
]
# 按指定格式打印结果
for category, links in results.items():
print(f"'{category}': [")
for link in links:
print(f" {link},")
print(" ],")
时时勤记录,岁月不饶人。日拱一卒,拱多了累