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

使用VBS+Chrome+CMD下载HTML源码并正则提取内容的问题

问题解决:VBS调用Chrome下载HTML并正则提取内容

问题1:VBS调用CMD执行Chrome命令失败

原命令存在以下错误:

  • 未使用cmd /c参数:直接调用cmd不会执行后续命令,必须加/c参数让CMD执行完命令后退出
  • 带空格的路径未转义:Program Files包含空格,VBS中需用双引号包裹路径,且内部双引号要转义为两个双引号
  • 命令逻辑错误:原命令中cd Program Files\...>chrome.exe的写法无效,需用&&连接cd和chrome命令,确保路径切换成功后再执行Chrome
  • 未等待命令执行完成:VBS默认异步执行,会导致文件未生成就开始读取,需在oShell.Run中添加第三个参数True等待命令执行完毕

修正后的CMD调用代码:

Set oShell = WScript.CreateObject("WScript.Shell")
oShell.Run "cmd /c cd ""C:\Program Files\Google\Chrome\Application"" && chrome.exe --headless --dump-dom --disable-gpu https://google.com >C:\temp\source.txt", 1, True

问题2:正则提取无输出

原代码的核心问题:

  • 逐行读取文件:若startString和endString不在同一行,逐行匹配会直接失败,应读取整个文件内容进行匹配
  • 正则表达式逻辑错误:原正则(^.*;startString=)(.*)(;endString.*)强制要求目标内容在同一行,且提取的是整个匹配结果而非中间的目标文本
  • 分组未正确使用:需通过SubMatches(1)提取startString=和;endString之间的内容,而非整个匹配项

修正后的正则提取代码:

' 读取整个文件内容
Dim fso, objFile, fullContent
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists("C:\temp\source.txt") Then
    Set objFile = fso.OpenTextFile("C:\temp\source.txt", ForReading)
    fullContent = objFile.ReadAll
    objFile.Close

    ' 正则提取目标内容
    Dim objRegExp, objMatches, out
    Set objRegExp = New RegExp
    ' 非贪婪匹配避免捕获多个endString之间的内容
    objRegExp.Pattern = ";startString=(.*?);endString"
    objRegExp.IgnoreCase = True
    objRegExp.Global = True

    Set objMatches = objRegExp.Execute(fullContent)
    out = ""
    If objMatches.Count > 0 Then
        For Each match In objMatches
            out = out & match.SubMatches(0) & vbCrLf
            WScript.Echo "found"
        Next
    End If
    WScript.Echo out
Else
    WScript.Echo "文件不存在,请检查Chrome命令是否执行成功"
End If

完整修正代码

' 调用Chrome下载HTML源码到本地
Set oShell = WScript.CreateObject("WScript.Shell")
oShell.Run "cmd /c cd ""C:\Program Files\Google\Chrome\Application"" && chrome.exe --headless --dump-dom --disable-gpu https://google.com >C:\temp\source.txt", 1, True

' 读取文件并提取目标内容
Dim fso, objFile, fullContent
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists("C:\temp\source.txt") Then
    Set objFile = fso.OpenTextFile("C:\temp\source.txt", ForReading)
    fullContent = objFile.ReadAll
    objFile.Close

    Dim objRegExp, objMatches, out
    Set objRegExp = New RegExp
    objRegExp.Pattern = ";startString=(.*?);endString"
    objRegExp.IgnoreCase = True
    objRegExp.Global = True

    Set objMatches = objRegExp.Execute(fullContent)
    out = ""
    If objMatches.Count > 0 Then
        For Each match In objMatches
            out = out & match.SubMatches(0) & vbCrLf
            WScript.Echo "found"
        Next
    End If
    WScript.Echo out
Else
    WScript.Echo "文件不存在,请检查Chrome命令是否执行成功"
End If

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 13:51:24