python 读取 chrome 历史记录并写入表格

当前环境:

Windows10 x64 + Python 3.7 + openpyxl 3.0.9 

import sqlite3
import time
import openpyxl


# 1 获取历史记录
def get_history():
    conn = sqlite3.connect(history)  # 连数据库
    cursor = conn.cursor()  # 获取游标
    cursor = conn.execute("SELECT id,url,title,visit_count,last_visit_time from urls order by last_visit_time desc ")

    rows = []
    for _id, url, title, visit_count, last_visit_time in cursor:
        row = {}
        row['id'] = _id
        row['url'] = url
        row['title'] = title
        row['visit_count'] = visit_count
        row['last_visit_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(
            last_visit_time / 1000000 - 11644473600)) if last_visit_time > 0 else 0
        rows.append(row)
    return rows


# 3 数据写入表格
def func_writeexcel(rows, filepath):
    # 写入数据表格
    workbook_w = openpyxl.load_workbook(filepath)
    worksheet_w = workbook_w.active

    for i in range(len(rows)):
        # 使用 append 方法
        data_single = (
        rows[i]['id'], rows[i]['url'], rows[i]['title'], rows[i]['visit_count'], rows[i]['last_visit_time'])
        worksheet_w.append(data_single)
        #
        '''
        row = worksheet_w.max_row + 1
        k = 1
        worksheet_w.cell(row, k, rows[i]['id'])
        k = k + 1
        worksheet_w.cell(row, k, rows[i]['url'])
        k = k + 1
        worksheet_w.cell(row, k, rows[i]['title'])
        k = k + 1
        worksheet_w.cell(row, k, rows[i]['visit_count'])
        k = k + 1
        worksheet_w.cell(row, k, rows[i]['last_visit_time'])
        '''
    # 保存数据
    workbook_w.save(filepath)


# 2 创建表格
def func_newexcel(filepath):
    try:
        # 创建表格
        workbook_w = openpyxl.Workbook()
        worksheet_w = workbook_w.active
        data = ['id', 'url', 'title', 'visit_count', 'last_visit_time']
        worksheet_w.append(data)
        # 保存
        workbook_w.save(filepath)
    except Exception as e:
        raise e


if __name__ == '__main__':
    # 数据库目录 C:\Users\xx\AppData\Local\Google\Chrome\User Data\Default 下的 History
    history = r'./History'
    # 表格目录
    filepath = r'./history.xlsx'
    # 1 获取历史记录
    rows = []
    rows = get_history()
    # 2 创建表格
    func_newexcel(filepath)
    # 3 数据写入表格
    func_writeexcel(rows, filepath)

其他 SQL 语句:

可以 把 History 直接拖入到 DB Browser for SQLite 这个软件,找到 urls 表,输入以下 sql 语句。

SELECT id, url, title, datetime((last_visit_time/1000000)-11644473600, 'unixepoch', 'localtime') AS last_visit_time FROM urls ORDER BY last_visit_time DESC

参考:
链接:https://juejin.cn/post/7133395183051210788

链接:https://zhuanlan.zhihu.com/p/93662611

链接:https://blog.csdn.net/weixin_45259896/article/details/122820285

你可能感兴趣的:(python,chrome,数据库)