如何从特定网站下载所有文件

时间:2019-06-20 09:21:46

标签: powershell download

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

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

我已经尝试过Invoke-WebRequest cmdlet,但是它没有显示任何链接,例如:

示例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文件。

1 个答案:

答案 0 :(得分:0)

这似乎可行,但是需要Internet Explorer com对象(基于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))")
}