是否可以使用 windows 批处理从 web html 页面解析数据?
假设我有一个网页:www.domain.com/data/page/1 页面源码html:
...
<div><a href="/post/view/664654"> ....
....
在这种情况下,我需要从网页获取/post/view/664654。
我的想法是遍历 www.domain.com/data/page/1 ... #(到某个给定的数字)并提取所有/post/view。然后我会得到一个链接列表,并从每个链接中提取 href 值(图像或视频)。
到目前为止,当我知道确切的链接时,我只能使用 wget 成功下载图像或视频。但我不知道如何(如果可能的话)解析 html 数据。
编辑
<body>
<nav>
<section>links I dont need</section>
</nav>
<article>
<section>links I need</section>
</article>
最佳答案
最好将结构化标记解析为分层对象,而不是将其抓取为平面文本。这样你就不会那么依赖你正在解析的数据的格式(无论是缩小的,间距改变的,等等)。
批处理语言不太适合解析标记语言,如 HTML、XML、JSON 等。在这种情况下,使用混合脚本并借用 JScript 或 PowerShell 方法来抓取你需要的数据。下面是一个演示批处理 + JScript 混合脚本的示例。使用 .bat 扩展名保存它并运行它。
@if (@CodeSection == @Batch) @then
@echo off & setlocal
set "url=http://www.domain.com/data/page/1"
for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0" "%url%"') do (
rem // do something useful with %%I
echo Link found: %%I
)
goto :EOF
@end // end batch / begin JScript hybrid code
// returns a DOM root object
function fetch(url) {
var XHR = WSH.CreateObject("Microsoft.XMLHTTP"),
DOM = WSH.CreateObject('htmlfile');
XHR.open("GET",url,true);
XHR.setRequestHeader('User-Agent','XMLHTTP/1.0');
XHR.send('');
while (XHR.readyState!=4) {WSH.Sleep(25)};
DOM.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
DOM.write(XHR.responseText);
return DOM;
}
var DOM = fetch(WSH.Arguments(0)),
links = DOM.getElementsByTagName('a');
for (var i in links)
if (links[i].href && /\/post\/view\//i.test(links[i].href))
WSH.Echo(links[i].href);
关于html - Windows 批处理/解析来自 html 网页的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36457549/