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

使用Selenium C#时如何隐藏Chrome任务栏图标(非无头模式)

解决Chrome Selenium有头模式下隐藏任务栏图标问题

以下是两个可行的解决方案,按优先级排序:

方案1:使用新版Chrome无头模式(优先推荐)

如果你的Chrome版本≥112,完全可以用新版无头模式替代有头模式,它支持完整的页面渲染和图片捕获,无需显示窗口,自然不存在任务栏图标问题。

代码示例:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
# 启用新版无头模式
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--window-size=1920,1080")

# 启动浏览器
driver = webdriver.Chrome(options=chrome_options)
driver.get("你的目标网站URL")

# 捕获验证码图片(示例:通过元素ID定位)
captcha_elem = driver.find_element("id", "captcha")
captcha_img_data = captcha_elem.screenshot_as_png

# 保存验证码到本地
with open("captcha.png", "wb") as f:
    f.write(captcha_img_data)

# 后续操作...
driver.quit()

方案2:有头模式下通过Windows API隐藏任务栏图标

如果必须使用有头模式,可借助pywin32库修改Chrome窗口的系统属性,实现任务栏图标隐藏,同时可将窗口移至屏幕可视区域外避免干扰。

步骤:

  1. 安装依赖库:
pip install pywin32
  1. 代码实现:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import win32gui
import win32con

# 配置Chrome选项
chrome_options = Options()
# 将窗口移至屏幕外(避免显示)
chrome_options.add_argument("--window-position=-32000,-32000")
chrome_options.add_argument("--window-size=800,600")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--disable-extensions")

# 启动浏览器
driver = webdriver.Chrome(options=chrome_options)
driver.get("你的目标网站URL")

# 获取Chrome窗口的系统句柄
def get_chrome_hwnd(driver):
    hwnd_list = []
    def enum_windows_callback(hwnd, extra):
        if win32gui.GetWindowText(hwnd) == driver.title:
            extra.append(hwnd)
        return True
    win32gui.EnumWindows(enum_windows_callback, hwnd_list)
    return hwnd_list[0] if hwnd_list else None

chrome_hwnd = get_chrome_hwnd(driver)
if chrome_hwnd:
    # 修改窗口扩展样式:移除任务栏显示属性,添加工具窗口属性
    current_style = win32gui.GetWindowLong(chrome_hwnd, win32con.GWL_EXSTYLE)
    # 取消任务栏显示
    current_style &= ~win32con.WS_EX_APPWINDOW
    # 设置为工具窗口(不在任务栏展示)
    current_style |= win32con.WS_EX_TOOLWINDOW
    # 应用样式修改
    win32gui.SetWindowLong(chrome_hwnd, win32con.GWL_EXSTYLE, current_style)
    # 刷新窗口状态
    win32gui.SetWindowPos(
        chrome_hwnd, None, 0, 0, 0, 0,
        win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_FRAMECHANGED
    )

# 后续验证码捕获等操作...
driver.quit()

注意事项:

  • 方案2仅适用于Windows系统;
  • 若窗口标题不唯一,可通过进程ID匹配窗口句柄(需额外引入psutil库),确保定位到正确的Chrome窗口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 11:23:11