ほんじゃらねっと

ダイエット中プログラマのブログ

Pocketからエクスポートしたブックマークをデータベースに取込むスクリプト

自分のブックマークを色々分析できるように、PocketのOptionsページから
エクスポートしたブックマークのリストをデータベースに取込む。

PythonでMySQLdbとBeautifulSoup4を使用。

テーブル

CREATE TABLE bookmarks (
id integer NOT NULL AUTO_INCREMENT,
title varchar(255),
url text,
created datetime,
PRIMARY KEY (id)
);

スクリプト(pocket_export2db.py)

!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import MySQLdb
from datetime import *
from bs4 import BeautifulSoup
DB_INFO = {
"host": "DBホスト名",
"db": "DB名",
"user": "DBユーザー名",
"passwd": "DBパスワード",
"charset": "DB文字コード"
}
def main():
argvs = sys.argv
if len(argvs) != 2:
print "Usage: python %s export_file_path" % argvs[0]
quit()
file_path = argvs[1]
soup = BeautifulSoup(open(file_path), from_encoding="utf-8")
connect = MySQLdb.connect(**DB_INFO)
connect.cursorclass = MySQLdb.cursors.DictCursor
cursor = connect.cursor()
for link in soup.find_all("a"):
href = link.get("href")
time_added = link.get("time_added")
tags = link.get("tags")
title = link.get_text()
print title
created = datetime.fromtimestamp(int(time_added))
res = cursor.execute("INSERT INTO bookmarks(title, url, created) VALUES(%s, %s, %s)", (title, href, created))
connect.commit()
cursor.close()
connect.close()
if __name__ == '__main__':
main()

使い方

python pocket_export2db.py エクスポートしたファイルのパス