周凯,个人博客

  • 前端
  • 嵌入式
  • 工具
  • 后端
  • 随笔
个人记录
  1. 首页
  2. python
  3. 正文

edge导出的收藏夹 使用python解析html为json

2024年 1月 22日 1042点热度 0人点赞 0条评论
  • Microsoft Edge浏览器导出的收藏夹文件通常是一个HTML格式的文件,里面包含了书签的标题、链接以及其他相关信息。要将这些信息转换为JSON格式,可以使用Python中的库,如BeautifulSoup来解析HTML,并利用json库来生成JSON数据。

  • 以下是一个基本的步骤示例:

  • 首先,确保你已经安装了beautifulsoup4和lxml库(如果还没有的话):

    pip install beautifulsoup4 lxml
  • 使用BeautifulSoup打开并解析HTML文件,找到包含书签信息的元素结构。

  • 提取每个书签的字段(例如:名称、URL等)并存储在字典中。

  • 将所有书签字典添加到一个列表中。

  • 使用json库将这个列表转换为JSON字符串并保存到文件中。

  • 示例:


Python
import json
from bs4 import BeautifulSoup

def html_to_json(html_file_path, json_file_path):
    with open(html_file_path, 'r', encoding='utf-8') as f:
        soup = BeautifulSoup(f.read(), 'lxml')

    # 根据Edge收藏夹HTML的实际结构来定位书签
    bookmarks = []
    for bookmark_tag in soup.find_all('a'):  # 这里假设书签是在a标签内
        title = bookmark_tag.text.strip()  # 书签名
        url = bookmark_tag.get('href')      # 书签链接

        # 创建字典并加入到bookmarks列表
        bookmark_dict = {'title': title, 'url': url}
        bookmarks.append(bookmark_dict)

    # 将bookmarks列表转换为JSON并写入文件
    with open(json_file_path, 'w', encoding='utf-8') as json_file:
        json.dump(bookmarks, json_file, ensure_ascii=False, indent=4)

# 调用函数进行转换
html_to_json("./resources/favorites_2024_1_22.html", "./resources/bookmarks.json")

🎯 拓展阅读提示

本文涉及的内容已同步至公众号后台,我会在那里分享更多深度内容和实用技巧

→ 点击关注:一行梦境

公众号二维码
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2024年 1月 22日

周凯

这个人很懒,什么都没留下

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2022-现在 周凯,个人博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蒙ICP备18004897号