使用Playwright在Firefox中打开多标签页异常:弹出多窗口
解决Firefox中Playwright打开新窗口而非标签页的问题
问题原因
Firefox中,每个Playwright的BrowserContext对应一个独立的浏览器窗口,你之前的代码通过context.new_page()创建页面时,Firefox会为该上下文单独启动窗口;而Chrome允许同一上下文的页面共享同一窗口的标签页,因此表现存在差异。
解决方案一:直接通过Browser实例创建页面
移除BrowserContext的创建步骤,直接调用browser.new_page(),Firefox会在同一个窗口中打开新标签页:
import time from playwright.sync_api import sync_playwright def run(playwright): firefox = playwright.firefox browser = firefox.launch(headless=False) page = browser.new_page() page.goto("https://google.com") new_tab = browser.new_page() new_tab.goto("https://playwright.dev") time.sleep(5) browser.close() with sync_playwright() as playwright: run(playwright)
解决方案二:复用Context并配置Firefox启动参数
如果需要保留BrowserContext(用于共享Cookie、本地存储等),可以在启动Firefox时添加-new-tab参数,强制在同一窗口打开新标签:
import time from playwright.sync_api import sync_playwright def run(playwright): firefox = playwright.firefox browser = firefox.launch(headless=False, args=["-new-tab"]) context = browser.new_context() page = context.new_page() page.goto("https://google.com") new_tab = context.new_page() new_tab.goto("https://playwright.dev") time.sleep(5) browser.close() with sync_playwright() as playwright: run(playwright)
内容的提问来源于stack exchange,提问作者Raisul Islam
相关产品推荐
相关产品推荐

