我想批量下载一些图片库。这些图像是免费提供的,无需任何许可。我一生都无法让它发挥作用。这是我到目前为止所拥有的。 $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
}
您需要提取匹配的值。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 } }
EDIT要下载它,你可以用另一个 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)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)