PowerShellのInvoke-WebRequestコマンドレットを使用して、ネットワーク上にあるWebページのHTMLソースコードをダウンロードする方法を解説します。
はじめに
本記事では、Invoke-WebRequestコマンドレットの基本的な使い方から、ネットワーク上にあるWebページのHTMLソースコードをダウンロードする方法までを解説しています。
Webページのコンテンツを取得する
Invoke-WebRequestコマンドレットの最もシンプルな使用方法となる、ネットワーク上にあるWebページのコンテンツを取得する方法を解説します。
書式
Invoke-WebRequest -Uri "WebページのURL"
サンプル
サンプルとして、当ブログのWebページである「PowerShellリファレンス」のコンテンツを取得してみます。
Invoke-WebRequest -Uri "https://syutaku.blog/powershell-reference/"
実行結果
コマンドの実行結果です。
*出力量が多いので多少削っています。
PS C:\workspace\PowerShell> Invoke-WebRequest -Uri "https://syutaku.blog/powershell-reference/"
StatusCode : 200
StatusDescription : OK
Content : <!doctype html><html lang="ja"><head>
<!-- wexal_pst_init.js does not exist -->
<!-- engagement_delay.js does not exist -->
<lin...
RawContent : HTTP/1.1 200 OK
Transfer-Encoding: chunked
Connection: keep-alive
x-pst-version: 3.1.14
x-pst-dynamic: EXPIRE/CREATE; 1.364 ms
x-...
Forms : {commentform, , , }
Headers : {[Transfer-Encoding, chunked], [Connection, keep-alive], [X-XSS-Protection, 1; mode=block], [X-Cont
ent-Type-Options, nosniff]...}
Images : {@{innerHTML=; innerText=; outerHTML=<img height="200"}
InputFields : {@{innerHTML=; innerText=; outerHTML=<input class="toc-checkbox"}
Links : {@{innerHTML=<span class="site-name-text" itemprop="name about">}
ParsedHtml : System.__ComObject
RawContentLength : 681450
リンク
レスポンスを取得する
前項で取得したコンテンツから、個々のレスポンスにアクセスする方法を説明します。
書式
Invoke-WebRequestコマンドレットの結果を変数に格納しています。
実行結果は「HtmlWebResponseObject」オブジェクトして返されます。
$response = Invoke-WebRequest -Uri "WebページのURL"
ステータスコードを取得する書式です。
$response.StatusCode
ヘッダーを取得する書式です。
$response.Headers
サンプル
前項と同様、当ブログのWebページである「PowerShellリファレンス」のコンテンツを取得します。
一旦、変数[response]に格納し、そこから「ステータスコード」と「ヘッダー」を取得してみます。
$response = Invoke-WebRequest -Uri "https://syutaku.blog/powershell-reference/" $response.StatusCode $response.Headers
実行結果
ステータスコードの取得結果です。
PS C:\workspace\PowerShell> $response.StatusCode 200
ヘッダーの取得結果です。
PS C:\workspace\PowerShell> $response.Headers Key Value --- ----- Transfer-Encoding chunked Connection keep-alive X-XSS-Protection 1; mode=block X-Content-Type-Options nosniff x-pst-version 3.1.14 x-pst-dynamic EXPIRE/CREATE; 1.316 ms x-b-cache B=nil:D=EXPIRE/CREATE X-Pst-Nginx-Cache MISS X-Debug-Donot-Cache 0 X-Debug-Too-Large 0 X-Debug-Non-Text 0 X-Page-Speed 1.13.35.2-0 Cache-Control max-age=0, no-cache Content-Type text/html; charset=UTF-8 Date Sun, 17 Jul 2022 12:34:31 GMT Server nginx
リンク
HTMLソースコードをダウンロードする
指定したURLのWebページを構成しているHTMLソースコードをダウンロードする方法を説明します。
書式
Invoke-WebRequest -Uri "WebページのURL" -OutFile "ダウンロード後のファイル名"
サンプル
WebページからダウンロードしたHTMLソースコードを、sample.htmlとして保存します。
Invoke-WebRequest -Uri "https://syutaku.blog/powershell-reference/" -OutFile "sample.html"






コメント