LoginSignup
0
1

More than 5 years have passed since last update.

PowerShell 2でスクレイピング

Last updated at Posted at 2019-03-20

環境

Windows7 + PowerShell 2

やりたいこと

ツールを導入できない環境でスクレイピングしたい。でも自前でhtmlパーサは書きたくない。
なお、Invoke-WebRequestはPowerShell 3からなので使用できない。

方法

COMオブジェクトのhtmlfileにIHTMLDocument2_writeで書き込めばDOM経由でHTMLの内容にアクセスできる。
書き込むHTMLはWebClientのDownloadStringで取得する。

# アクセス先
$url = "http://google.com"

# WebClientを準備
$wc = New-Object System.Net.WebClient
$wc.Encoding = [System.Text.Encoding]::GetEncoding("UTF-8")

# htmlfileオブジェクトを準備
$content = $wc.DownloadString($url)
$htmlfile = New-Object -com "htmlfile"
$htmlfile.IHTMLDocument2_write($content)

# htmlfileオブジェクトを操作して必要な要素を見つけだす。
# 今回は google 検索ボタン を参照している。
# htmlfileのDOM操作は独特でgetElementByIdがうまく使えない。
# getElementsByTagNameは有効なのでそれを手掛かりに探す。
# querySelector なんて便利なものは存在しない。
$htmlfile.getElementsByTagName("form")[0].getElementsByTagName("input")[6].value
0
1
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
0
1