使用powershell从HTML网站获取图像链接
我想批量下载一些图片库。这些图像是免费提供的,不需要任何权限。我一辈子都不能让它工作。这就是我目前所拥有的。$pattern spit out是整个HTML行,而不仅仅是图像链接。你能给我一些建议吗?出于测试目的,循环被设置为仅运行一次。循环将遍历以数字形式组织的所有页面使用powershell从HTML网站获取图像链接,html,image,parsing,powershell,download,Html,Image,Parsing,Powershell,Download,我想批量下载一些图片库。这些图像是免费提供的,不需要任何权限。我一辈子都不能让它工作。这就是我目前所拥有的。$pattern spit out是整个HTML行,而不仅仅是图像链接。你能给我一些建议吗?出于测试目的,循环被设置为仅运行一次。循环将遍历以数字形式组织的所有页面 # Variables $i=1 # Webpage Counter $j=1 # Image Counter $rootDir = "http://website.com/sport/galler
# 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
}
选择字符串
返回具有属性的对象。将其发送至获取会员
,查看您有什么好东西。您需要签出matches属性,例如$pattern.matches
。查看。中的示例9,您需要提取匹配的值Select String
返回对象,当您echo
它时,发生的是$pattern.ToString()
ToString()
返回行,而不是匹配值。这将仅返回所有链接:
Get-Content $webpagetxt | 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(urlink,localfile)命令下载它们。
$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)
}