用python获取谷歌浏览器的浏览历史

python小项目 · 03-05

可以使用Python的sqlite3模块来获取谷歌浏览器的浏览历史。在Windows操作系统上,谷歌浏览器的浏览历史数据存储在一个SQLite数据库文件中。

以下是一个示例代码,可以获取谷歌浏览器的浏览历史:

import os
import sqlite3
from datetime import datetime, timedelta

# 获取Chrome浏览器的历史记录
def get_chrome_history():
    # 判断操作系统类型
    if os.name == "posix":  # macOS
        history_db = os.path.expanduser("~/Library/Application Support/Google/Chrome/Default/History")
    elif os.name == "nt":  # Windows
        history_db = os.path.join(os.environ["LOCALAPPDATA"], r"Google\Chrome\User Data\Default\History")
    else:
        raise RuntimeError("Unsupported operating system")

    # 连接数据库
    conn = sqlite3.connect(history_db)
    cursor = conn.cursor()

    # 计算时间范围
    end_time = datetime.now()
    start_time = end_time - timedelta(days=7)

    # 查询历史记录
    query = f"SELECT urls.url, visits.visit_time FROM urls, visits WHERE urls.id = visits.url AND visits.visit_time > {int(start_time.timestamp()) * 1000000} AND visits.visit_time < {int(end_time.timestamp()) * 1000000}"
    cursor.execute(query)

    # 获取结果
    results = cursor.fetchall()

    # 关闭数据库连接
    cursor.close()
    conn.close()

    # 处理结果
    for result in results:
        url = result[0]
        visit_time = result[1] / 1000000
        visit_time_str = datetime.fromtimestamp(visit_time).strftime("%Y-%m-%d %H:%M:%S")

        print(f"{visit_time_str} - {url}")

这个示例代码首先根据操作系统类型获取Chrome浏览器的历史记录数据库文件路径,然后使用sqlite3模块连接数据库。接着,计算时间范围,使用SQL查询语句获取指定时间范围内的历史记录。最后,关闭数据库连接并打印结果。

获取浏览历史需要访问Chrome浏览器的历史记录数据库文件,因此需要有足够的权限,并且需要注意防范恶意操作。另外,不同版本的Chrome浏览器可能历史记录数据库文件路径不同,需要根据实际情况修改代码。

  1. l 03-06

    共道人间惆怅事,不知今夕是何年。

  2. admin (作者)  03-06

    When the dawn is close inside, we never say good-bye and never see again.

Theme Jasmine by Kent Liao