tableタグで作成された表を解析しcsvなどにしたい場合はありませんか?
本資料では、単純なHTMLを用意しHTMLファイルのスクレイピングをしてみます。
PS C:\> $PSVersionTable.PSVersion Major Minor Build Revision ----- ----- ----- -------- 5 1 18362 145
curlやwgetのようにURLを指定して情報を取得する場合は、以下の記事を参考にしてください。
以下のHTMLファイルを用意しました。
sample.html sample.zip
<html> <head> <title>sample</title> </head> <body> sample table <table> <tr> <th>No</th><th>value1</th><th>value2</th> </tr> <tr> <td>1</td><td>11</td><td>12</td> </tr> <tr> <td>2</td><td>21</td><td>22</td> </tr> <tr> <td>3</td><td>31</td><td>32</td> </tr> </table> </body> </html>
htmlファイルをSystem.Xml.XmlDocumentオブジェクトとして読み込むためには、以下の構文になります。
$obj = [xml](Get-Content ファイル名)
上記の通り、htmlファイルをXmlDocumentオブジェクトに読み込み操作することになります。
以下は、用意したsample.htmlをDドライブ直下に置いてPowerShellにて操作した実行例となります。
PS D:\> $obj = [xml](Get-Content D:\sample.html) #br
PS D:\> $obj html ---- html #br
PS D:\> $obj.html head body ---- ---- head body #br
PS D:\> $obj.html.body #text table ----- ----- ... table
PS D:\> $obj.html.body.'#text' sample table
PS D:\> $obj.html.body.table tr -- {tr, tr, tr, tr} PS D:\> $obj.html.body.table.tr.count 4
$table = $obj.html.body.table $tr_count = $table.tr.Count for ($i=0; $i -lt $tr_count; $i++) { if ($i -eq 0) { $table.tr[$i].th } else { $table.tr[$i].td } }
$table = $obj.html.body.table $tr_count = $table.tr.Count for ($i=0; $i -lt $tr_count; $i++) { if ($i -eq 0) { $t = $table.tr[$i].th } else { $t = $table.tr[$i].td } $t[0] + "," + $t[1] + "," + $t[2] }
以上、XmlDocumentオブジェクトを使って、HTMLをスクレイピングするサンプルでした。