使用PowerShell从HTML网站获取图像链接

4

我想批量下载一些图片库。这些图片是免费提供的,不需要任何权限。但我却无论如何都无法下载成功。目前我已经尝试了以下方法,但$pattern输出的是整个HTML行,而不仅仅是图片链接。你能给我一些指引吗?为测试目的,循环只设置运行一次。循环会遍历所有数字组织的页面。

# Variables
$i=1        # Webpage Counter
$j=1        # Image Counter
$rootDir = "http://website.com/sport/galleries/"
$saveDir = "C:\Users\user\Desktop\"
$webpagetxt = "C:\Users\user\Desktop\page.txt"
$links = "C:\Users\user\Desktop\links.txt"
$regex = "http://website.com/galleries/[0-9]*/[^\.]*.JPG"

# Create folder to download to
#New-Item -Name SiouxSportsGalleries -ItemType directory

# Start Web Client
$client = New-Object System.Net.WebClient

# Main loop to get image links and download
    For($i=10; $i -le 10; $i++){

        # Download source code of the web page.
        $url = $rootDir+$i+'.htm'
        $webclient = new-object System.Net.WebClient
        $webpage = $webclient.DownloadString($url)
        $webpage > "$webpagetxt"

    # Parse web page and find image link.
       $pattern = Get-Content $webpagetxt | Select-String -pattern $regex -Allmatches
       echo "This is the link" $pattern
    #$pattern > $links

 }
2个回答

4
你需要提取匹配到的值。 Select-String 返回对象,当你使用echo命令时,它会输出$pattern.ToString()ToString()返回整个行,而不是匹配的值。这将仅返回所有链接:
Get-Content $webpagetxt | Select-String -pattern $regex -Allmatches | % { $_.Matches | % { $_.Value } }

顺便提一下,如果你只是为了获取网页内容而保存了它然后用get-content重新打开,其实你可以直接在换行符处将字符串拆分成数组(如果这是你保存的唯一原因的话)。 :-)

$webpage -split "`n" | Select-String -pattern $regex -Allmatches | % { $_.Matches | % { $_.Value } }

编辑 如果要下载它,您可以使用另一个foreach循环进行扩展:

$rootDir = "http://website.com/sport/galleries/"
$saveDir = "C:\Users\user\Desktop\"
$webpage -split "`n" | Select-String -pattern $regex -Allmatches | % { $_.Matches | % { $_.Value } } | % {
    #Get local path
    $local = $_.Replace($rootDir, $saveDir)
    #Create path
    $file = New-Item $local -ItemType file -Force
    #Download
    $wb.DownloadFile($_, $file.FullName)
}

谢谢。我尝试了一下,它可以工作。现在我只需要想办法访问那个数组,将http//website.com/sport/galleries替换为C:\Users\user\Desktop\,这样我就可以使用$.client.downloadFile(urlLink,localfile)命令下载它们。 - xIHammerIx

0

Select-String 会返回一个带有属性的对象。将其发送到 Get-Member,以查看您拥有的好东西。您需要检查匹配属性,例如 $pattern.matches。请查看 文档 中的示例9。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接