12
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShellで、特定サイトのファイルを一括ダウンロードする

Posted at

用途

あるページに、PDF等が大量に置いてあるが、一つ一つダウンロードする手間が惜しい。
シェルとかで、一気にダウンロードできたらなー、という時に使います。

ただ、PDFである必要はなく、書き直せば他のファイル形式でも可能です。

バージョン

PowerShell 3.0以降で利用してください。

必要な処理

指定ページの内容を解釈する処理と、ファイルをダウンロードする処理が必要です。

処理

Invoke-WebRequestを使います。

なお、下記の例で出てくる$url変数には、対象とするサイトのURLが入ります。
また、例外処理は省いています。

指定ページの内容を解釈する

PowerShellを使う場合、Linksプロパティによってリンクの一覧を取得できるため、解釈作業はこれだけで済みます。

SiteCrawl.ps1
# Webページから、PDFへのリンクを取得
$response = Invoke-WebRequest -Uri $uri -UseBasicParsing

$links = $response.Links | Where-Object {$_.href -like "*.pdf"} | Select-Object -ExpandProperty href

リンク一覧→.pdfのみ→hrefのみ、とリストを作成します。

ファイルをダウンロード

SiteCrawl.ps1
# 個々のファイルダウンロード
foreach($link in $links){
    #ファイル名抽出
    $fileName = Split-Path $link -Leaf
    
    #保存先パス作成(フォルダ + ファイル名)
    $outFilePath = Join-Path $savePath $fileName

    #DL対象ファイルのURL取得(Uriの機能で、絶対パスと相対パスをくっつける)
    $downloadUrl = New-Object System.Uri ($uri, $link)
    
    Invoke-WebRequest -Uri $downloadUrl.AbsoluteUri -OutFile $outFilePath
}

絶対パスと相対パスの結合は、手作業では辛いので、.NETのUriクラスを使います。

また、ファイルをダウンロードする場合は、Invoke-WebRequest-OutFileを付けます。

SSL/TLSのエラーが出る場合

処理を開始する前に、以下の文を実行してみましょう。

SiteCrawl.ps1
# SSL/TLSのエラーが発生する場合
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

参照:リンク

全文(GitHubリンク)

12
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?