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

如何用Python获取各类浏览器中当前打开网站的URL?

获取已打开浏览器标签页URL的Python方案

Selenium确实无法读取已运行的浏览器实例的标签页数据——它只能操控自己启动的浏览器进程。下面是针对主流浏览器的可行实现方案:

Chrome/Edge(Chromium内核)

Chromium系浏览器支持远程调试接口,需先开启调试模式,再通过Python读取数据:

  1. 开启浏览器远程调试:

    • Windows:右键浏览器快捷方式,在目标栏末尾追加 --remote-debugging-port=9222,示例:"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222
    • macOS:终端执行 /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
    • Linux:终端执行 google-chrome --remote-debugging-port=9222
  2. Python获取URL代码:

    import json
    import urllib.request
    
    def get_chromium_urls():
        # 从调试接口获取页面列表
        with urllib.request.urlopen('http://localhost:9222/json') as resp:
            pages = json.load(resp)
        # 过滤提取标签页的URL
        return [page['url'] for page in pages if page['type'] == 'page']
    
    if __name__ == '__main__':
        print(get_chromium_urls())
    

Firefox

Firefox需通过Marionette协议开启远程调试,再用Selenium连接已运行实例:

  1. 配置Firefox调试:

    • 地址栏输入about:config,设置:
      • devtools.debugger.remote-enabled = true
      • devtools.debugger.prompt-connection = false(关闭连接弹窗)
      • devtools.chrome.enabled = true
    • 启动Firefox时追加参数:--marionette --start-debugger-server=2828
  2. Python获取URL代码:

    from selenium import webdriver
    from selenium.webdriver.firefox.options import Options
    
    def get_firefox_urls():
        options = Options()
        options.add_argument('--marionette')
        # 连接已运行的Firefox实例
        driver = webdriver.Firefox(options=options, command_executor='http://localhost:2828')
        urls = []
        # 遍历所有标签页
        for handle in driver.window_handles:
            driver.switch_to.window(handle)
            urls.append(driver.current_url)
        driver.quit()
        return urls
    
    if __name__ == '__main__':
        print(get_firefox_urls())
    

Safari

Safari需开启开发者工具的远程自动化功能:

  1. 开启调试:

    • 偏好设置 → 高级 → 勾选"在菜单栏中显示开发菜单"
    • 开发菜单中选择"允许远程自动化"
  2. Python获取URL代码:

    from selenium import webdriver
    from selenium.webdriver.safari.options import Options
    
    def get_safari_urls():
        options = Options()
        options.add_argument('--remote-debugging-port=27753')
        driver = webdriver.Safari(options=options)
        urls = []
        for handle in driver.window_handles:
            driver.switch_to.window(handle)
            urls.append(driver.current_url)
        driver.quit()
        return urls
    
    if __name__ == '__main__':
        print(get_safari_urls())
    

关键注意事项

  • 所有方案都要求浏览器提前开启对应调试模式,出于安全和权限限制,无法直接读取未配置调试的浏览器实例
  • 不同浏览器的调试端口、配置项可能随版本更新变化,需对应调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:28:24