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

如何使用Playwright启动非隐身模式的Chromium浏览器会话

Playwright启动非隐身模式Chromium会话方案

问题原因

你当前代码启动的始终是隐身模式,是因为Playwright默认调用chromium.launch()创建的浏览器实例,后续生成的上下文都是临时隔离的隐身上下文,不会持久化任何用户数据,表现和隐身模式完全一致。

解决方案

使用持久化上下文APIchromium.launch_persistent_context()替代原有launch() + new_context()的组合,指定本地用户数据存储目录即可启动非隐身模式,所有浏览数据(Cookie、登录状态、缓存等)都会持久保存在指定目录下,下次启动可直接复用。

修改后代码示例

from behave import *
from playwright.sync_api import sync_playwright
import time


class session_driver:
    driver = None

    def open_browser(self, url):
        playW_sync_instace = sync_playwright().start()
        global context
        # 替换为launch_persistent_context,指定用户数据目录,非隐身模式核心配置
        context = playW_sync_instace.chromium.launch_persistent_context(
            user_data_dir="./chrome_user_data", # 自定义本地存储路径,自动创建
            headless=False,
            record_video_dir="videos/",
            record_video_size={"width": 640, "height": 480}
        )
        # 直接从持久化上下文创建页面,无需额外调用new_context
        self.driver = context.new_page()
        self.driver.goto(url)

可选配置

如果需要调用你本地安装的Chrome/Chromium而非Playwright内置的浏览器版本,可以在launch_persistent_context参数中添加executable_path配置,值为本地浏览器的可执行文件路径,比如Windows下是C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe,Mac下是/Applications/Google Chrome.app/Contents/MacOS/Google Chrome。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:27:05