🗺️ 需求背景
集团考核各子公司辖内员工对指定网页的访问量,为了排名不至于垫底😔,于是琢磨如何简单有效地刷点流量。原理就是定期执行脚本,调用系统浏览器(默认为 Chrome)打开指定 URL。为了不影响牛马的日常工作(突然弹出浏览器是有点吓人😄),选择使用无头模式
。
🫥 Chrome 无头模式

Chrome 无头模式是一种 在没有图形界面的情况下运行 Chrome 浏览器 的模式。它常用于 自动化测试、网页抓取、性能分析、截图 / PDF 生成等场景,因为它比启动完整 GUI 浏览器更轻量、速度更快,也可以运行在没有显示器的服务器环境中。
如何开启
如需使用无头模式,请传递 --headless 命令行标志:chrome --headless
。
示例
shell
chrome --headless --disable-gpu --remote-debugging-port=9222 https://example.com
常用参数:
参数 | 说明 |
---|---|
--headless |
开启无头模式 |
--disable-gpu |
禁用 GPU 加速(部分平台需要) |
--remote-debugging-port |
开启远程调试端口 |
--no-sandbox |
(Linux 容器里常用)禁用沙箱 |
👨💻 完整代码
bat
@echo off
for /f %%p in ('powershell -Command "Start-Process chrome.exe -ArgumentList '--headless --disable-gpu http://localhost:3000/' -PassThru | %%{$_.Id}"') do (
set "pid=%%p"
)
timeout /t 5 >nul
taskkill /pid %pid% /f
我们用 powershell
启动进程,直接拿到 PID,等待 5 秒后,关闭进程。
进阶版
我们改造上述脚本,改成一个可重复调用的通用模板(传入 URL、延时秒数等参数)。
bat
@echo off
setlocal enabledelayedexpansion
:: 检查参数
if "%~1"=="" (
echo 用法: %~nx0 [URL] [秒数]
echo 示例: %~nx0 https://example.com 5
exit /b 1
)
set "URL=%~1"
if "%~2"=="" (
set "DELAY=5"
) else (
set "DELAY=%~2"
)
:: 用 PowerShell 启动 Chrome 无头模式并拿到 PID
for /f %%p in ('
powershell -Command "Start-Process chrome.exe -ArgumentList '--headless --disable-gpu %URL%' -PassThru | %%{$_.Id}"
') do (
set "PID=%%p"
)
if not defined PID (
echo 无法启动 Chrome,请检查是否已安裝 chrome.exe 並配置到 PATH
exit /b 1
)
echo Chrome 已启动 (PID=%PID%),将在 %DELAY% 秒后关闭...
:: 等待指定秒数
timeout /t %DELAY% >nul
:: 关闭进程
taskkill /pid %PID% /f >nul 2>&1
echo Chrome 已关闭
endlocal
使用示例:chrome_headless.bat https://example.com 5