python导出chrome书签到markdown文件的实例代码

yipeiwu_com5年前Python基础

python导出chrome书签到markdown文件,主要就是解析chrome的bookmarks文件,然后拼接成markdown格式的字符串,最后输出到文件即可。以下直接上代码,也可以在 py-chrome-bookmarks-markdown 中直接参见源码。

from json import loads
import argparse
from platform import system
from re import match
from os import environ
from os.path import expanduser
# 过滤name
filter_name_list = {'My work', '书签栏', 'websites'}
html_escape_table = {
  "&": "&",
  '"': """,
  "'": "'",
  ">": ">",
  "<": "<",
}
output_file_template = """
<h3>书签目录</h3>
{catelog}
{bookmark_bar}
{other}
"""
# 如需本地调试可注释掉这一段 START
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
                 description="python导出chrome书签到markdown文件.")
parser.add_argument("input_file", type=argparse.FileType('r', encoding='utf-8'), nargs="?",
          help="读取书签的位置,可以指定文件位置(相对路径,绝对路径都可以),非必填,默认为Chrome的默认书签位置")
parser.add_argument("output_file", type=argparse.FileType('w', encoding='utf-8'),
          help="读取书签的位置,可以指定文件位置(相对路径,绝对路径都可以),必填")
args = parser.parse_args()
if args.input_file:
  input_file = args.input_file
else:
  if system() == "Darwin":
    input_filename = expanduser("~/Library/Application Support/Google/Chrome/Default/Bookmarks")
  elif system() == "Linux":
    input_filename = expanduser("~/.config/google-chrome/Default/Bookmarks")
  elif system() == "Windows":
    input_filename = environ["LOCALAPPDATA"] + r"\Google\Chrome\User Data\Default\Bookmarks"
  else:
    print('Your system ("{}") is not recognized. Please specify the input file manually.'.format(system()))
    exit(1)
  try:
    input_file = open(input_filename, 'r', encoding='utf-8')
  except IOError as e:
    if e.errno == 2:
      print("The bookmarks file could not be found in its default location ({}). ".format(e.filename) +
         "Please specify the input file manually.")
      exit(1)
output_file = args.output_file
# 如需本地调试可注释掉这一段 END
# 本地调试可以指定文件名测试 START
# input_filename = 'C:/Users/Administrator/AppData/Local/Google/Chrome/User Data/Default/Bookmarks'
# input_file = open(input_filename, 'r', encoding='utf-8')
# output_file_name = 'test2.md'
# output_file = open(output_file_name, 'w', encoding='utf-8')
# 本地调试可以指定文件名测试 END
# 目录
catelog = list()
def html_escape(text):
  return ''.join(html_escape_table.get(c, c) for c in text)
def html_for_node(node):
  # 判断url和children即判断是否包含在文件夹中
  if 'url' in node:
    return html_for_url_node(node)
  elif 'children' in node:
    return html_for_parent_node(node)
  else:
    return ''
def html_for_url_node(node):
  if not match("javascript:", node['url']):
    return '- [{}]({})\n'.format(node['name'], node['url'])
  else:
    return ''
def html_for_parent_node(node):
  return '{0}\n\n{1}\n'.format(filter_catelog_name(node),
                 ''.join([filter_name(n) for n in node['children']]))
# 过滤文件夹
def filter_name(n):
  if n['name'] in filter_name_list:
    return ''
  else:
    return html_for_node(n)
# 过滤目录名
def filter_catelog_name(n):
  if n['name'] in filter_name_list:
    return ''
  else:
    catelog.append('- [{0}](#{0})\n'.format(n['name']))
    return '<h4 id={0}>{0}</h4>'.format(n['name'])
contents = loads(input_file.read())
input_file.close()
bookmark_bar = html_for_node(contents['roots']['bookmark_bar'])
other = html_for_node(contents['roots']['other'])
catelog_str = ''.join(a for a in catelog)
output_file.write(output_file_template.format(catelog=catelog_str, bookmark_bar=bookmark_bar, other=other))

导出示例: https://github.com/kent666a/kent-resources/blob/master/bookmarks.md

总结

以上所述是小编给大家介绍的python导出chrome书签到markdown文件的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

使用Python横向合并excel文件的实例

使用Python横向合并excel文件的实例

起因: 有一批数据需要每个月进行分析,数据存储在excel中,行标题一致,需要横向合并进行分析。 数据示意: 具有多个 代码: # -*- coding: utf-8 -*- "...

Python Multiprocessing多进程 使用tqdm显示进度条的实现

Python Multiprocessing多进程 使用tqdm显示进度条的实现

1.背景 在python运行一些,计算复杂度比较高的函数时,服务器端单核CPU的情况比较耗时,因此需要多CPU使用多进程加快速度 2.函数要求 笔者使用的是:pathos.multipr...

python求质数列表的例子

因为写别的程序想要一边遍历一边删除列表里的元素,就写了一个这样的程序进行测试,这样写出来感觉还挺简洁的,就发出来分享一下。 代码 l=list(range(2,1000)) for...

浅析Python中的多重继承

浅析Python中的多重继承

继承是面向对象编程的一个重要的方式,因为通过继承,子类就可以扩展父类的功能。 回忆一下Animal类层次的设计,假设我们要实现以下4种动物:    ...

Python实现去除列表中重复元素的方法总结【7种方法】

这里首先给出来我很早之前写的一篇博客,Python实现去除列表中重复元素的方法小结【4种方法】,感兴趣的话可以去看看,今天是在实践过程中又积累了一些方法,这里一并总结放在这里。 由于内容...