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

如何实时获取当前浏览器页面URL以进行解析?

实时获取浏览器当前页面URL的简便方法

以下几种方法比你之前用的坐标操作、OCR截图要简便得多:

1. 快捷键+剪贴板法(跨平台通用)

利用浏览器的地址栏选中快捷键(Windows/Linux用Ctrl+L,macOS用Cmd+L),结合复制快捷键把URL存到剪贴板,再读取剪贴板内容。这种方法无需依赖系统API,代码简单,适配绝大多数浏览器:

import pyperclip
import keyboard

def get_current_browser_url():
    # 选中地址栏
    keyboard.press_and_release('ctrl+l')  # macOS替换为'cmd+l'
    # 复制地址栏内容
    keyboard.press_and_release('ctrl+c')
    # 从剪贴板读取URL
    return pyperclip.paste()

注意:调用前确保浏览器窗口处于激活状态。

2. Windows平台:通过系统API直接读取控件内容

针对Chrome、Edge等Chromium系浏览器,可以通过win32库直接定位地址栏控件并读取文本,完全不需要模拟鼠标键盘操作:

import win32gui
import win32con

def get_chrome_edge_url():
    # 找到Chromium系浏览器的主窗口(Chrome类名Chrome_WidgetWin_1,Edge为Chrome_WidgetWin_0)
    hwnd = win32gui.FindWindow("Chrome_WidgetWin_1", None) or win32gui.FindWindow("Chrome_WidgetWin_0", None)
    if not hwnd:
        return None
    # 定位地址栏控件
    addr_bar = win32gui.FindWindowEx(hwnd, 0, "Chrome_OmniboxView", None)
    if not addr_bar:
        return None
    # 获取控件文本长度
    text_len = win32gui.SendMessage(addr_bar, win32con.WM_GETTEXTLENGTH, 0, 0) + 1
    # 读取文本内容
    buffer = win32gui.PyMakeBuffer(text_len)
    win32gui.SendMessage(addr_bar, win32con.WM_GETTEXT, text_len, buffer)
    return buffer[:text_len-1].decode('utf-8')

3. macOS平台:通过AppleScript调用浏览器原生接口

macOS可以直接用AppleScript调用浏览器的API,获取当前活跃标签页的URL,稳定性极高:

from AppKit import NSAppleScript

def get_mac_browser_url(browser_name="Chrome"):
    # 编写AppleScript脚本
    script_content = f'''
    tell application "{browser_name}"
        return URL of active tab of front window
    end tell
    '''
    # 执行脚本并获取结果
    apple_script = NSAppleScript.alloc().initWithSource_(script_content)
    result, error = apple_script.executeAndReturnError_(None)
    if error:
        return None
    return result.stringValue()

使用时可以传入"Safari"、"Firefox"等浏览器名称,适配不同软件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:47:17