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比较文件夹比另一同名文件夹多出的文件并复制出来的方法
Mar 05 Python
简介Django框架中可使用的各类缓存
Jul 23 Python
Python安装使用命令行交互模块pexpect的基础教程
May 12 Python
解决Python中字符串和数字拼接报错的方法
Oct 23 Python
Python Socket编程详细介绍
Mar 23 Python
Python使用arrow库优雅地处理时间数据详解
Oct 10 Python
python调用Matplotlib绘制分布点并且添加标签
May 31 Python
使用django-guardian实现django-admin的行级权限控制的方法
Oct 30 Python
Python turtle画图库&amp;&amp;画姓名实例
Jan 19 Python
python实现对变位词的判断方法
Apr 05 Python
使用Pycharm(Python工具)新建项目及创建Python文件的教程
Apr 26 Python
Python QT组件库qtwidgets的使用
Nov 02 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
php strrpos()与strripos()函数
2013/08/31 PHP
php中addslashes函数与sql防注入
2014/11/17 PHP
PHP保存带BOM文件的方法
2015/02/12 PHP
php常用图片处理类
2016/03/16 PHP
使用PHP反射机制来构造&quot;CREATE TABLE&quot;的sql语句
2019/03/21 PHP
PHP实现数组向任意位置插入,删除,替换数据操作示例
2019/04/05 PHP
用prototype实现的简单小巧的多级联动菜单
2007/03/24 Javascript
javascript 去字符串空格终极版(支持utf8)
2009/11/14 Javascript
jquery animate图片模向滑动示例代码
2011/01/26 Javascript
30个让人兴奋的视差滚动(Parallax Scrolling)效果网站
2012/03/04 Javascript
javascript 3d 逐侦产品展示(核心精简)
2014/03/26 Javascript
JavaScript实现按照指定长度为数字前面补零输出的方法
2015/03/19 Javascript
JS实现简洁、全兼容的拖动层实例
2015/05/13 Javascript
JavaScript设计模式初探
2016/01/07 Javascript
bootstrap日历插件datetimepicker使用方法
2016/12/14 Javascript
jQuery实现复选框的全选和反选
2017/02/02 Javascript
微信小程序本地缓存数据增删改查实例详解
2017/05/24 Javascript
checkbox:click事件触发span元素内容改变的方法
2017/09/11 Javascript
解决使用Vue.js显示数据的时,页面闪现原始代码的问题
2018/02/11 Javascript
Puppet的一些技巧
2018/09/17 Javascript
浅析Vue 中的 render 函数
2020/02/28 Javascript
[26:21]浴火之凤-TI4世界冠军Newbee战队纪录片
2014/08/07 DOTA
python的keyword模块用法实例分析
2015/06/30 Python
深入分析python中整型不会溢出问题
2018/06/18 Python
关于numpy数组轴的使用详解
2019/12/05 Python
python中K-means算法基础知识点
2021/01/25 Python
百丽国际旗下购物网站:优购
2017/02/28 全球购物
Fabletics官网:美国运动服饰品牌,由好莱坞女演员凯特·哈德森创立
2019/10/19 全球购物
2014年母亲节寄语
2014/05/07 职场文书
区政府领导班子个人对照检查材料
2014/09/25 职场文书
建筑专业毕业生求职信
2014/09/30 职场文书
入党介绍人意见怎么写
2015/06/03 职场文书
汽车车尾标语大全
2015/08/11 职场文书
如何使用flask将模型部署为服务
2021/05/13 Python
详解MySQL集群搭建
2021/05/26 MySQL
《艾尔登法环》1.03.3补丁上线 碎星伤害调整
2022/04/07 其他游戏