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

如何让Selenium Firefox驱动在新标签而非新窗口打开URL?

解决Firefox驱动通过window.open在新标签页而非独立窗口打开URL的问题

你遇到的问题核心是偏好设置冲突以及部分参数配置错误,同时新版本Selenium已不推荐混用FirefoxProfile和Options,以下是修正后的完整代码:

from selenium import webdriver

options = webdriver.firefox.options.Options()
# 保留原下载目录设置
options.set_preference("browser.download.folderList", 2)
# 设置语言
options.set_preference('intl.accept_languages', 'en-GB')
# 核心:强制在新标签页打开新窗口
options.set_preference("browser.link.open_newwindow", 3)
options.set_preference("browser.link.open_newwindow.restriction", 0)
# 外部链接同样在新标签页打开
options.set_preference("browser.link.open_external", 3)
# 允许页面打开新标签页(之前设为True会阻止,需改为False)
options.set_preference("browser.block.target_new_window", False)
options.add_argument("--headless")

driver = webdriver.Firefox(options=options)

# 原window.open代码无需修改
for url in page_lists:
    driver.execute_script('window.open("{0}", "_blank");'.format(url))

关键修正点说明:

  • 弃用FirefoxProfile:新版本Selenium中FirefoxProfile已被标记为过时,统一使用Options管理所有偏好设置可避免配置覆盖或冲突。
  • 修正browser.block.target_new_window参数:你之前设置为True会阻止页面打开新窗口/标签页,完全违背需求,需改为False。
  • 核心偏好参数组合:browser.link.open_newwindow=3配合restriction=0会强制Firefox将所有新窗口请求转为新标签页,覆盖默认的独立窗口行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:20:31