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

MacOS下如何通过Playwright连接已登录的Chrome实例?

解决Playwright通过CDP连接Chrome后新页面未保持登录状态的问题

问题原因

使用browser.new_page()创建页面时,会生成一个全新的隔离浏览器上下文,这个上下文和你手动登录的上下文完全独立,没有继承cookie、会话等登录数据,因此新页面会显示未登录状态。

解决方案

1. 复用已有的浏览器上下文创建页面

修改代码,获取Chrome中已存在的上下文(手动登录的会话就在这个上下文里),然后在该上下文中新建页面:

from playwright.sync_api import sync_playwright
import time


def connect_to_chrome_debugger():
    with sync_playwright() as p:
        browser = p.chromium.connect_over_cdp("http://localhost:9234")
        
        # 获取已存在的浏览器上下文列表
        existing_contexts = browser.contexts
        if not existing_contexts:
            print("未找到已存在的浏览器上下文")
            browser.close()
            return
            
        # 使用第一个已存在的上下文(手动登录的会话在此上下文内)
        target_context = existing_contexts[0]
        page = target_context.new_page()

        page.goto("https://gmail.com")
        time.sleep(10)
        print(page.title())

        page.close()
        # 不要关闭浏览器,保留手动登录状态
        # browser.close()


if __name__ == "__main__":
    connect_to_chrome_debugger()

2. 直接使用已打开的页面(可选)

如果Chrome中已经打开了登录后的页面,可以直接获取并操作该页面,无需新建:

from playwright.sync_api import sync_playwright
import time


def connect_to_chrome_debugger():
    with sync_playwright() as p:
        browser = p.chromium.connect_over_cdp("http://localhost:9234")
        
        # 获取已打开的页面列表
        existing_pages = browser.pages
        if not existing_pages:
            print("未找到已打开的页面")
            browser.close()
            return
            
        # 使用第一个已打开的页面
        page = existing_pages[0]
        page.goto("https://gmail.com")
        time.sleep(10)
        print(page.title())

        # 不要关闭页面和浏览器,保留登录状态
        # page.close()
        # browser.close()


if __name__ == "__main__":
    connect_to_chrome_debugger()

3. 启动Chrome时指定用户数据目录(可选)

确保启动的Chrome加载你平时使用的用户配置(包含登录状态),可以在启动命令中添加--user-data-dir参数:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9234 --user-data-dir="/Users/你的用户名/Library/Application Support/Google/Chrome/Default"

替换你的用户名为你的系统用户名,这样启动的Chrome会保留你的登录会话数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 00:37:35