首页 > 解决方案 > 如何从特定网站下载所有文件

问题描述

以下网站提供了一些 .xlsx 统计数据:https://www.ifo.de/umfragen/zeitreihen 链接文件夹每月调整一次。

如何使用 PowerShell 下载所有文件?

我已经尝试了Invoke-WebRequestcmdlet,但它没有显示任何链接,例如:

示例 1 未在 download_link.txt 中提供任何条目

$u = 'https://www.ifo.de/umfragen/zeitreihen/'
$l = (Invoke-WebRequest –Uri $u).Links | ? href -like *xlsx*
Set-Content c\test_path\download_link.txt -Value $l
$l | select -Unique href | % {
    #get file name
    $name = $l | ? href -eq $_.href | select -First 1 -ExpandProperty innerHtml
    "going to DL $name"
    #get actual DL link
    $mp3 = Invoke-WebRequest $_.href |
           select -ExpandProperty Links |
           ? href -like *xlsx |
           select -ExpandProperty href
    #$mp3 = (Invoke-WebRequest ($_.href  | select -Unique href | select -    First 1 -ExpandProperty href)).Links | ? href -like *xlsx* | select -ExpandProperty href
    "real file is $xlsx, downloading..."
    timeout 5
    Invoke-WebRequest -Uri $xlsx -OutFile c\test_path\$name -Verbose
}

示例 2 也不下载任何 .xlsx 文件

$IOTD = ((Invoke-WebRequest -Uri ‘https://www.ifo.de/umfragen/zeitreihen/’).Links | Where {$_.href -like “*.xlsx*”}).href
(New-Object System.Net.WebClient).DownloadFile($IOTD,'c\test_path\')

最好的情况是使用第一个脚本将下载链接动态写入文本文件,然后下载所有提供的 .xlsx 文件。

标签: powershelldownload

解决方案


这似乎可行,但需要 Internet Explorer com-object(基于https://stackoverflow.com/a/30975153/932282):

function Get-InternetDocument
{
    param (
        [Parameter(Mandatory=$true)]
        [String] $Url
    )

    $ie = New-Object -ComObject "InternetExplorer.Application"
    $ie.Visible = $false
    $ie.Navigate($Url)

    while ($ie.Busy -or $ie.ReadyState -lt 4) {
        Start-Sleep -Milliseconds 200
    }

    return $ie.Document
}

$url = "https://www.ifo.de/umfragen/zeitreihen/"
$document = Get-InternetDocument -Url $url

$links = $document.getElementsByTagName("a")
$links = $links | Where-Object { $_.href -match ".xlsx`$" } | Select-Object -ExpandProperty "href"

foreach ($link in $links)
{
    (New-Object -TypeName "System.Net.WebClient").DownloadFile($link, "c:\temp\$([System.IO.Path]::GetFileName($link))")
}

推荐阅读