You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Javascript或Python监控并捕获浏览器请求的URL?

可用的JavaScript/Python请求监控工具包及实现方案

JavaScript方案

页面内请求拦截(仅当前页面)

如果只需要监控单个页面发起的请求,无需额外工具包,直接重写浏览器原生请求API即可捕获链接:

// 拦截 fetch 请求
const originalFetch = window.fetch;
window.fetch = async (...args) => {
  const requestUrl = args[0] instanceof Request ? args[0].url : args[0];
  saveUrlToTxt(requestUrl);
  return originalFetch(...args);
};

// 拦截 XMLHttpRequest 请求
const originalXhrOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
  saveUrlToTxt(url);
  originalXhrOpen.call(this, method, url);
};

// 将URL追加写入txt文件
function saveUrlToTxt(url) {
  // 读取已有内容实现追加逻辑
  fetch('request_urls.txt')
    .then(res => res.text().catch(() => ''))
    .then(existingContent => {
      const newContent = existingContent + url + '\n';
      const blob = new Blob([newContent], { type: 'text/plain' });
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = 'request_urls.txt';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    });
}

浏览器扩展(全浏览器监控)

要监控整个浏览器的所有请求,需要开发浏览器扩展,利用浏览器原生webRequestAPI实现:

// background.js 扩展后台脚本
chrome.webRequest.onBeforeRequest.addListener(
  (details) => {
    // 存储请求URL到本地存储
    chrome.storage.local.get('requestUrls', (data) => {
      const urls = data.requestUrls || [];
      urls.push(details.url);
      chrome.storage.local.set({ requestUrls: urls });
    });
  },
  { urls: ["<all_urls>"] }
);

// popup.js 扩展弹窗脚本(用于导出txt)
document.getElementById('exportBtn').addEventListener('click', () => {
  chrome.storage.local.get('requestUrls', (data) => {
    const content = data.requestUrls?.join('\n') || '';
    const blob = new Blob([content], { type: 'text/plain' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = 'browser_requests.txt';
    a.click();
  });
});

Python方案

Mitmproxy(代理式监控)

mitmproxy是可脚本化的HTTP/HTTPS代理,能拦截所有经过代理的请求,用Python脚本处理并保存:

  1. 安装依赖:pip install mitmproxy
  2. 编写脚本save_urls.py:
from mitmproxy import http

class UrlSaver:
    def request(self, flow: http.HTTPFlow) -> None:
        # 追加写入URL到txt文件
        with open("all_requests.txt", "a", encoding="utf-8") as f:
            f.write(f"{flow.request.pretty_url}\n")

addons = [UrlSaver()]
  1. 运行代理:mitmdump -s save_urls.py
  2. 将浏览器代理设置为127.0.0.1:8080,之后所有请求都会被捕获并写入文件。

Playwright(浏览器自动化监控)

通过浏览器自动化工具直接监听请求并保存,以Playwright为例:

  1. 安装依赖:pip install playwright,执行playwright install安装浏览器驱动
  2. 编写监控脚本:
from playwright.sync_api import sync_playwright

def monitor_browser_requests():
    with sync_playwright() as p:
        # 启动非无头模式浏览器,方便用户操作
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()
        
        # 监听所有请求并实时写入文件
        with open("browser_requests.txt", "a", encoding="utf-8") as log_file:
            def log_request(request):
                log_file.write(f"{request.url}\n")
                log_file.flush()
            
            page.on("request", log_request)
            
            # 打开初始页面,用户可自由浏览
            page.goto("https://www.google.com")
            input("浏览完成后按回车退出...")
        
        browser.close()

if __name__ == "__main__":
    monitor_browser_requests()

内容的提问来源于stack exchange,提问作者Laspeed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:50:20