如何在Python中通过WebExtension API获取浏览器历史记录?
Selenium调用WebExtension History API获取浏览器历史记录的问题解决
问题根源
你混淆了两个完全不同的history对象:
- 你通过
driver.execute_script调用的history是当前网页的DOM History对象,它仅负责当前页面的会话导航(比如前进、后退、修改URL),只有back()、forward()、pushState()等方法,根本没有search()。 - 你参考的文档里的
history.search()是浏览器扩展专用的History API,这个API只能在WebExtension的背景脚本或扩展上下文里运行,无法直接通过网页的JavaScript访问。
正确实现方案
要通过Selenium获取浏览器历史记录,必须借助WebExtension来调用专属API,再把结果传递给Selenium的页面上下文。以下是具体步骤:
1. 编写WebExtension
创建一个简单的扩展,用于获取历史记录并响应Selenium的请求:
manifest.json(以Chrome/Edge的Manifest V3为例)
{ "manifest_version": 3, "name": "History Fetcher", "version": "1.0", "background": { "service_worker": "background.js" }, "permissions": ["history"], "host_permissions": ["<all_urls>"] }
background.js(扩展背景脚本)
// 监听来自页面的消息 chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.action === "fetchHistory") { // 调用扩展History API获取历史记录(空text表示获取全部,maxResults可调整) chrome.history.search({ text: "", maxResults: 200 }, (historyItems) => { sendResponse(historyItems); }); return true; // 异步响应需返回true } });
2. Python Selenium代码
加载扩展并通过消息通信获取历史记录:
from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.webdriver import WebDriver # 配置浏览器加载扩展 options = Options() # 替换为你的扩展文件夹绝对路径 options.add_argument("--load-extension=/absolute/path/to/your/extension") driver = WebDriver(options=options) # 打开任意页面(需要页面存在才能注入脚本发消息) driver.get("https://example.com") # 执行脚本向扩展发送请求并获取历史记录 get_history_script = """ return new Promise(resolve => { chrome.runtime.sendMessage({ action: "fetchHistory" }, response => { resolve(response); }); }); """ history_list = driver.execute_script(get_history_script) # 处理并打印历史记录 for record in history_list: print(f"标题: {record.get('title', '无标题')}") print(f"URL: {record['url']}") print(f"最后访问时间: {record['lastVisitTime']}\n") driver.quit()
注意事项
- Firefox的扩展API使用
browser.history而非chrome.history,需要修改背景脚本代码以兼容。 - 扩展必须申请
history权限,否则无法调用API。 - 部分浏览器可能要求扩展打包为.xpi或.crx文件才能加载,需根据浏览器要求调整。
内容的提问来源于stack exchange,提问作者David Frick
相关产品推荐
相关产品推荐

