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

Playwright启动浏览器时应用告警弹窗不显示的问题求助

问题描述

使用Playwright启动Chromium浏览器后,点击页面上的按钮(如marketReport)无法触发预期的alert弹窗,但手动刷新页面后点击正常。同时Playwright环境的控制台找不到execute函数,手动启动的浏览器则能找到。已调整浏览器启动参数但无效,希望实现无需手动干预即可触发弹窗。

浏览器启动代码

self.browser = self.playwright.chromium.launch(
                headless = False,
                slow_mo = 2000,
                devtools= True,
        args = [
            
            r"--user-data-dir=C:\Users\user\AppData\Local\Temp\chrome_profile",
             "--allow-pre-commit-input" ,
        "--disable-background-networking","--disable-backgrounding-occluded-windows","--disable-blink-features=AutomationControlled",
        "--disable-browser-side-navigation","--disable-client-side-phishing-detection","--disable-default-apps" ,"--disable-dev-shm-usage","--disable-extensions",
        "--disable-features=VizDisplayCompositor","--disable-gpu","--disable-hang-monitor" ,"--disable-infobars" ,
        "--disable-popup-blocking" ,"--disable-prompt-on-repost","--disable-setuid-sandbox" ,"--disable-software-rasterizer","--disable-sync","--disable-web-security","--enable-automation",
        "--enable-logging ","--ignore-certificate-errors" ,"--log-level=0 "" --no-first-run",
        "--no-sandbox","--no-service-autorun","--password-store=basic","--proxy-bypass-list=*" ,"--proxy-server='direct://'","--remote-debugging-port=0" ,"--test-type" ,
        "--use-mock-keychain","--user-data-"
        ]
        self._browser = BrowserType.create_browser(browser_type)
        self._context = self._browser.new_context(              
                no_viewport = True,
                accept_downloads=True,
                bypass_csp=True,
                ignore_https_errors=True,
                 permissions=["geolocation", "notifications"],
            )
        self._context.clear_cookies()
         self._context.add_cookies([{
         'name': 'name',
         'value': 'value',
         'domain': 'domain',
         'path': '/'
         }])
  
        self._page = self._context.new_page()

页面按钮HTML代码

<!-- BUTTONS START -->
<br>
&nbsp;
<input type="button" id="rules" name="rules" value="Rules" class="button-raised-primary" onclick="execute(this.form, 'rules');" accesskey="" style="">
&nbsp;
<input type="button" id="marketReport" name="marketReport" value="Launch market report" class="button-raised-primary" onclick="execute(this.form, 'marketReport');" accesskey="" style="">
&nbsp;
<input type="button" id="factReport" name="factReport" value="Launch fact report" class="button-raised-primary" onclick="execute(this.form, 'factReport');" accesskey="" style="">
</tr>
</tbody></table>
</div>
<!-- BUTTONS END -->
解决方案

1. 修复浏览器启动参数错误

你的启动参数存在解析异常和冗余问题,修正后可避免脚本加载异常:

  • 移除--log-level=0 "" --no-first-run中的空引号
  • 删除不完整的--user-data-参数
  • 移除冲突的--enable-automation和测试模式的--test-type参数

修正后的args示例:

args = [
    r"--user-data-dir=C:\Users\user\AppData\Local\Temp\chrome_profile",
    "--allow-pre-commit-input",
    "--disable-background-networking",
    "--disable-backgrounding-occluded-windows",
    "--disable-blink-features=AutomationControlled",
    "--disable-browser-side-navigation",
    "--disable-client-side-phishing-detection",
    "--disable-default-apps",
    "--disable-dev-shm-usage",
    "--disable-extensions",
    "--disable-features=VizDisplayCompositor",
    "--disable-gpu",
    "--disable-hang-monitor",
    "--disable-infobars",
    "--disable-popup-blocking",
    "--disable-prompt-on-repost",
    "--disable-setuid-sandbox",
    "--disable-software-rasterizer",
    "--disable-sync",
    "--disable-web-security",
    "--enable-logging",
    "--ignore-certificate-errors",
    "--log-level=0",
    "--no-first-run",
    "--no-sandbox",
    "--no-service-autorun",
    "--password-store=basic",
    "--proxy-bypass-list=*",
    "--proxy-server='direct://'",
    "--remote-debugging-port=0",
    "--use-mock-keychain"
]

2. 等待页面脚本完全加载

核心问题是execute函数未被正确加载,需等待函数全局可用后再点击按钮:

# 导航到页面后,等待execute函数全局存在
self._page.wait_for_function("typeof window.execute === 'function'")
# 执行点击操作
self._page.click("#marketReport")

3. 监听并处理alert弹窗

Playwright默认会自动关闭弹窗,需提前监听并处理:

# 监听alert事件,可选择接受或打印弹窗内容
self._page.on("dialog", lambda dialog: dialog.accept())
# 或查看弹窗内容:
# self._page.on("dialog", lambda dialog: print(dialog.message()) or dialog.accept())

# 等待脚本加载后点击
self._page.wait_for_function("typeof window.execute === 'function'")
self._page.click("#marketReport")

4. 修正浏览器实例重复创建问题

代码中同时调用playwright.chromium.launch()和BrowserType.create_browser()属于重复创建,统一使用Playwright标准启动流程:

# 正确初始化流程
self.browser = self.playwright.chromium.launch(
    headless=False,
    slow_mo=2000,
    devtools=True,
    args=args  # 使用修正后的参数
)
self._context = self.browser.new_context(
    no_viewport=True,
    accept_downloads=True,
    bypass_csp=True,
    ignore_https_errors=True,
    permissions=["geolocation", "notifications"],
)
self._context.clear_cookies()
self._context.add_cookies([{
    'name': 'name',
    'value': 'value',
    'domain': 'domain',
    'path': '/'
}])
self._page = self._context.new_page()
# 导航到目标页面
self._page.goto("你的目标URL")

5. 彻底禁用CSP策略

若页面CSP仍阻止脚本加载,可在启动参数中添加--disable-content-security-policy强制禁用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:44:54