需要在批处理文件中从 HTML 文档中解析出字符串

Need to parse out string from HTML document in a batch file

我尝试搜索,但找不到任何符合我需要的内容。

这是我的 HTML 文件的摘录:

<div id="pair_today">
    <div class="left_block">
        <div class="tpl_box">
            <h1 style="margin-top:5px;color:#ec1b1b;">
            <span style="font-size:15px;color:#000;">1 Australian Dollar =</span><br /> 93.663 Japanese Yen</h1>

                        <span style="display:inline-block; margin-top:10px; text-align:right; align:right; font-size:12px; color:#9c9c9c">rate on Fri, 6 March, 2015 15:58:20 (AEDT)</span>

           <a href="http://fx-rate.net/AUD/JPY/currency-transfer/" title="Currenty Transfer from Australia to Japan" style="float:right" class="btn" onclick="ga('send','event', {'eventCategory': 'CurrencyTransfer', 'eventAction' : 'click','eventLabel':'Today Box'});"><span class="btn-ico btn-ico-go">Get Rate</span></a>
           </span>

我需要解析第 5 行的 93.663 值。 每次我必须 运行 脚本时,这个值都会不同,所以我认为正则表达式是专门针对这个值的最佳方式。

我一直在研究 for /f 循环,但我不知道如何在脚本中实现正则表达式。

谢谢大家!

使用 Windows 脚本宿主(VBscript 或 JScript)。使用 htmlfile COM 对象。解析 DOM。然后您可以根据需要使用正则表达式按摩 innerText

给你。将其另存为 .bat 文件,根据需要修改 set "htmlfile=test.html" 行,然后修改 运行。 (源自 this answer。WSH 中 htmlfile COM 对象的文档很少;但如果您想了解更多信息,请关注面包屑。)

@if (@CodeSection == @Batch) @then

@echo off
setlocal

set "htmlfile=test.html"

rem // invoke JScript hybrid code and capture its output
for /f %%I in ('cscript /nologo /e:JScript "%~f0" "%htmlfile%"') do set "converted=%%I"

echo %converted%

rem // end main runtime
goto :EOF

@end // end batch / begin JScript chimera

var fso = WSH.CreateObject('scripting.filesystemobject'),
    DOM = WSH.CreateObject('htmlfile'),
    htmlfile = fso.OpenTextFile(WSH.Arguments(0), 1),
    html = htmlfile.ReadAll();

DOM.write(html);
htmlfile.Close();

var scrape = DOM.getElementById('pair_today').getElementsByTagName('h1')[0].innerText;
WSH.Echo(scrape.match(/^.*=\s+(\S+).*$/)[0]);

你知道,只要你正在调用 Windows Script Host,如果你正在使用 wget 或类似的方式获取你的 html 文件,你就可以摆脱它依赖。除非您正在下载的页面使用了一系列复杂的 cookie 和会话重定向,否则您可以将 wget 替换为 Microsoft.XMLHTTP COM 对象并通过 XHR 下载页面(或者像那些头脑不太清醒的人所说的那样,Ajax). (基于 fetch.bat。)

@if (@CodeSection == @Batch) @then

@echo off
setlocal

set "from=%~1"
set "to=%~2"
set "URL=http://host.domain/currency?from=%from%&to=%to%"

for /f "delims=" %%I in ('cscript /nologo /e:jscript "%~f0" "%URL%"') do set "conv=%%I"

echo %conv%

rem // end main runtime
goto :EOF

@end // end batch / begin JScript chimera

var x = WSH.CreateObject("Microsoft.XMLHTTP"),
    DOM = WSH.CreateObject('htmlfile');

x.open("GET",WSH.Arguments(0),true);
x.setRequestHeader('User-Agent','XMLHTTP/1.0');
x.send('');
while (x.readyState!=4) {WSH.Sleep(50)};

DOM.Write(x.responseText);

var scrape = DOM.getElementById('pair_today').getElementsByTagName('h1')[0].innerText;
WSH.Echo(scrape.match(/^.*=\s+(\S+).*$/)[0]);