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


Posted in Python onDecember 27, 2017

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异常处理总结
Aug 15 Python
Python脚本实现DNSPod DNS动态解析域名
Feb 14 Python
django将图片上传数据库后在前端显式的方法
May 25 Python
使用anaconda的pip安装第三方python包的操作步骤
Jun 11 Python
Django缓存系统实现过程解析
Aug 02 Python
Python re 模块findall() 函数返回值展现方式解析
Aug 09 Python
Python 日志logging模块用法简单示例
Oct 18 Python
python中栈的原理及实现方法示例
Nov 27 Python
关于tf.TFRecordReader()函数的用法解析
Feb 17 Python
Python socket连接中的粘包、精确传输问题实例分析
Mar 24 Python
python中查看.db文件中表格的名字及表格中的字段操作
Jul 07 Python
通过实例了解Python异常处理机制底层实现
Jul 23 Python
Python类的继承和多态代码详解
Dec 27 #Python
快速查询Python文档方法分享
Dec 27 #Python
Java及python正则表达式详解
Dec 27 #Python
python matplotlib画图实例代码分享
Dec 27 #Python
python爬虫使用cookie登录详解
Dec 27 #Python
Python爬虫番外篇之Cookie和Session详解
Dec 27 #Python
Python并发编程协程(Coroutine)之Gevent详解
Dec 27 #Python
You might like
德生PL450的电路分析和低放电路的改进办法
2021/03/02 无线电
php面向对象全攻略 (四)构造方法与析构方法
2009/09/30 PHP
php使用curl发送json格式数据实例
2013/12/17 PHP
php安装扩展mysqli的实现步骤及报错解决办法
2017/09/23 PHP
网页常用特效代码整理
2006/06/23 Javascript
ExtJS TabPanel beforeremove beforeclose使用说明
2010/03/31 Javascript
主页面中的两个iframe实现鼠标拖动改变其大小
2013/04/16 Javascript
jquery打开直接跳到网页最下面、最低端实现代码
2013/04/22 Javascript
JS创建事件的三种方法(实例代码)
2016/05/12 Javascript
json定义及jquery操作json的方法
2016/09/29 Javascript
微信小程序 action-sheet底部菜单详解
2016/10/27 Javascript
js实现下一页页码效果
2017/03/07 Javascript
Javascript继承机制详解
2017/05/30 Javascript
jQuery 禁止表单用户名、密码自动填充功能
2017/10/30 jQuery
vue-cli脚手架config目录下index.js配置文件的方法
2018/03/13 Javascript
axios向后台传递数组作为参数的方法
2018/08/11 Javascript
在webstorm开发微信小程序之使用阿里自定义字体图标的方法
2018/11/15 Javascript
Vue开发中常见的套路和技巧总结
2020/11/24 Vue.js
Python远程桌面协议RDPY安装使用介绍
2015/04/15 Python
Python函数式编程指南(三):迭代器详解
2015/06/24 Python
Python利用turtle库绘制彩虹代码示例
2017/12/20 Python
python 日期操作类代码
2018/05/05 Python
Tensorflow Summary用法学习笔记
2020/01/10 Python
利用Python优雅的登录校园网
2020/10/21 Python
缅甸网上购物:Shop.com.mm
2017/12/05 全球购物
.net C#面试题
2012/08/28 面试题
运动会广播稿200米
2014/01/27 职场文书
幼教简历自我评价
2014/01/28 职场文书
巾帼建功标兵事迹材料
2014/05/11 职场文书
商务英语专业毕业生求职信
2014/07/06 职场文书
公安局副政委班子个人对照检查材料
2014/10/04 职场文书
恰同学少年观后感
2015/06/08 职场文书
社区服务活动感想
2015/08/11 职场文书
创业计划书之养殖业
2019/10/11 职场文书
如何用JavaScript实现一个数组惰性求值库
2021/05/05 Javascript
浅谈Golang 切片(slice)扩容机制的原理
2021/06/09 Golang