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

 更新时间:2017年12月27日 15:59:06   作者:深蓝浅蓝的天 关注  
python导出chrome书签到markdown文件,主要就是解析chrome的bookmarks文件,然后拼接成markdown格式的字符串,最后输出到文件即可。下面给大家分享实例代码,需要的朋友参考下

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 实现Harris角点检测算法

    python 实现Harris角点检测算法

    这篇文章主要介绍了python 实现Harris角点检测算法,帮助大家更好的利用python处理图像,感兴趣的朋友可以了解下
    2020-12-12
  • python画图把时间作为横坐标的方法

    python画图把时间作为横坐标的方法

    今天小编就为大家分享一篇python画图把时间作为横坐标的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • 让python json encode datetime类型

    让python json encode datetime类型

    python2.6+ 自带的json模块,不支持datetime的json encode,每次都需要手动转为字符串,很累人,我们可以自己封装一个简单的方法处理此问题。
    2010-12-12
  • 浅谈Python中函数的参数传递

    浅谈Python中函数的参数传递

    下面小编就为大家带来一篇浅谈Python中函数的参数传递。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-06-06
  • Python时间的精准正则匹配方法分析

    Python时间的精准正则匹配方法分析

    这篇文章主要介绍了Python时间的精准正则匹配方法,结合实例形式对比分析了Python针对时间格式相关正则匹配技巧,需要的朋友可以参考下
    2017-08-08
  • 使用python生成大量数据写入es数据库并查询操作(2)

    使用python生成大量数据写入es数据库并查询操作(2)

    这篇文章主要介绍了使用python生成大量数据写入es数据库并查询操作,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-09-09
  • python中subplot大小的设置步骤

    python中subplot大小的设置步骤

    matploglib能够绘制出精美的图表,有时候我们希望把一组图放在一起进行比较,就需要用到matplotlib中提供的subplot了,这篇文章主要给大家介绍了关于python中subplot大小的设置方法,需要的朋友可以参考下
    2021-06-06
  • 浅谈keras通过model.fit_generator训练模型(节省内存)

    浅谈keras通过model.fit_generator训练模型(节省内存)

    这篇文章主要介绍了浅谈keras通过model.fit_generator训练模型(节省内存),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06
  • Python协程操作之gevent(yield阻塞,greenlet),协程实现多任务(有规律的交替协作执行)用法详解

    Python协程操作之gevent(yield阻塞,greenlet),协程实现多任务(有规律的交替协作执行)用法详解

    这篇文章主要介绍了Python协程操作之gevent(yield阻塞,greenlet),协程实现多任务(有规律的交替协作执行)用法,结合实例形式较为详细的分析了协程的功能、原理及gevent、greenlet实现协程,以及协程实现多任务相关操作技巧,需要的朋友可以参考下
    2019-10-10
  • Python之列表推导式最全汇总(下篇)

    Python之列表推导式最全汇总(下篇)

    这篇文章主要介绍了Python之列表推导式最全汇总(下篇),本文章内容详细,通过案例可以更好的理解列表推导式的相关知识,本模块分为了三部分,本次为下篇,需要的朋友可以参考下
    2023-01-01

最新评论