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

Python subprocess调用Chrome打开新标签页异常问题求助

解决方案

方案1:一次性传递所有URL给Chrome命令行

Chrome命令行支持一次性传入多个URL,当已有Chrome窗口运行时,这些URL会直接在当前窗口的新标签页打开,而非新建窗口。只需把你需要的所有网址(包括chrome://newtab)按顺序作为参数传给chrome.exe即可。

示例代码:

import subprocess

# Chrome安装路径,根据你的实际位置调整
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
# 待打开的URL列表,最后一项为目标新标签页
target_urls = [
    "https://www.example.com",
    "https://github.com",
    "chrome://newtab"
]

# 构造启动命令
launch_cmd = [chrome_path] + target_urls
# 启动Chrome,不等待进程执行完毕
subprocess.Popen(launch_cmd, shell=False)

方案2:分步骤打开,强制在当前窗口新增标签

如果需要分批次打开网址(比如先加载常用站点,再打开新标签页),可以先启动Chrome打开第一个URL,后续每个URL都通过--new-tab参数调用Chrome,确保在现有窗口内打开新标签。

示例代码:

import subprocess
import time

chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
target_urls = [
    "https://www.example.com",
    "https://github.com",
    "chrome://newtab"
]

# 打开第一个URL,初始化Chrome窗口
subprocess.Popen([chrome_path, target_urls[0]])
# 短暂等待确保Chrome窗口加载完成(时间可根据实际情况调整)
time.sleep(1)

# 循环打开剩余URL,每个都强制新建标签
for url in target_urls[1:]:
    subprocess.Popen([chrome_path, "--new-tab", url])
    time.sleep(0.2)  # 避免命令发送过快导致异常

Selenium问题的可选修复方案

如果必须使用Selenium,针对你遇到的问题可尝试以下调整:

  • 加载本地Chrome配置文件:初始化ChromeDriver时指定用户数据目录,示例:
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    chrome_options = Options()
    # 替换为你的Chrome用户数据路径,格式参考:C:\Users\<你的用户名>\AppData\Local\Google\Chrome\User Data
    chrome_options.add_argument(r"user-data-dir=C:\Users\YourName\AppData\Local\Google\Chrome\User Data")
    chrome_options.add_argument(r"profile-directory=Default")  # 指定默认配置文件
    # 移除自动化运行提示
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_experimental_option('useAutomationExtension', False)
    
    driver = webdriver.Chrome(options=chrome_options)
    # 依次打开多个标签
    driver.get("https://www.example.com")
    driver.execute_script("window.open('https://github.com');")
    driver.execute_script("window.open('chrome://newtab');")
    
  • 规避Windows Defender拦截:将官方匹配版本的ChromeDriver加入Defender信任列表,避免使用未签名的驱动文件。

不过对比来看,直接用subprocess调用Chrome命令行更轻量,无自动化提示和拦截风险,更适合开机启动场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 16:25:15