使用正则表达式从Powershell中的网页获取链接

时间:2018-03-22 00:47:03

标签: regex powershell webclient-download

以下是我在powershell中的代码,用于获取网页中的链接。间歇性地,我得到“无法索引到空数组”异常。这段代码有什么问题吗?需要帮助。

$Download = $wc.DownloadString($Link) 
$List = $Download -split "<a\s+" | %{ [void]($_ -match "^href=[`'`"]([^`'`">\s]*)"); $matches[1] }

1 个答案:

答案 0 :(得分:2)

您不需要自己解析任何内容(正如评论中指出的那样,您无法首先使用正则表达式解析HTML)。使用Invoke-Webrequest获取页面;它返回的对象的一个​​属性是页面上所有链接的集合,已经为你解析了。

示例:

$Link = "https://stackoverflow.com/questions/49418802/getting-links-from-webpage-in-powershell-using-regular-expression";
Invoke-WebRequest -Uri $Link | Select-Object -ExpandProperty links;

或者,如果您只需要URL,您可以更简洁地做到这一点:

$Link = "https://stackoverflow.com/questions/49418802/getting-links-from-webpage-in-powershell-using-regular-expression";
(Invoke-WebRequest -Uri $Link).links.href;