我正在尝试使用 VBS 和 Chrome 下载 HTML 源代码,将其保存到本地磁盘并使用正则表达式提取两个单词(startString - endString)之间的文本。这就是我所拥有的:
'run cmd command
Set oShell = WScript.CreateObject("WScript.Shell")
oShell.Run "cmd c: & cd Program Files\Google\Chrome\Application>chrome.exe --headless --dump-dom --enable-logging --disable-gpu https://google.com >C:\temp\source.txt"
'read txt
Dim objFile, fso
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFile = fso.OpenTextFile("C:\temp\source.txt", ForReading)
'RegEx
Dim objRegExp
Set objRegExp = New RegExp 'Set our pattern
objRegExp.Pattern = "(^.*;startString=)(.*)(;endString.*)"
objRegExp.IgnoreCase = True
objRegExp.Global = True
Do Until objFile.AtEndOfStream
strSearchString = objFile.ReadLine
Dim objMatches
Set objMatches = objRegExp.Execute(strSearchString)
If objMatches.Count > 0 Then
out = out & objMatches(0) &vbCrLf
WScript.Echo "found"
End If
Loop
WScript.Echo out
objFile.Close
问题 1:我在使用 CMD 和 VBS 时遇到问题,如果我打开控制台,导航到 C: 和 Chrome.exe,则命令工作正常。 问题2:out Echo总是空
使用 InStr 代替 RegExp 可以简化代码。此外,如注释中所示,原始代码中的 Run 命令缺少
/c
,不必要地更改目录,并且缺少 bWaitOnReturn。另请注意,如果要显示的字符串超过 64K,WScript.Echo 将无法显示任何内容。 MsgBox 将始终显示字符串的前 1023 个字符。这是使用 InStr 重写的代码:
Set oWSH = WScript.CreateObject("WScript.Shell")
oWSH.Run "Cmd.exe /c ""C:\Program Files\Google\Chrome\Application\chrome.exe"" --headless --dump-dom --enable-logging --disable-gpu https://google.com >C:\temp\source.txt",,True
Set oFSO = CreateObject("Scripting.FileSystemObject")
Contents = oFSO.OpenTextFile("C:\temp\source.txt").ReadAll
StartString = "https://store.google.com"
EndString = "https://mail.google.com"
StartPos = InStr(Contents,StartString)
FoundText = ""
If StartPos>0 Then
EndPos = InStr(StartPos,Contents,EndString)
If EndPos > StartPos Then FoundText = Mid(Contents,StartPos,EndPos-StartPos)
End If
WScript.Echo FoundText