Google Map を使って住所を正規化する(その2)

昨日のエントリでは WebBrowser を使いましたが、WebBrowser を使う場合 DocumentCompleted イベントの待機の問題が発生します。Application.DoEvents も極力使いたくないし、WPF でも使いたい。そこで本日は WebRequestHTML DOM を使ったサンプルを考えてみました。

基本的には以下のようになるかと思います。DOM の使い方については以下の記事を参考にさせて頂きました。参照設定に Microsoft.mshtml の追加が必要になります。

参考記事【VB.NET】WebClientとHTMLDocumentを利用してHTMLを解析する

Option Explicit On
Option Strict On

Imports System.Net
Imports System.IO
Imports mshtml

Module Module1
    Sub Main()
        Dim address = Console.ReadLine()
        Dim enc = System.Text.Encoding.GetEncoding("Shift_JIS")
        Dim req = WebRequest.Create("http://maps.google.co.jp/maps?hl=ja&q=" + address)

        Using res = req.GetResponse(), st = res.GetResponseStream()
            Using sr = New StreamReader(st, enc)
                Dim buf = New System.Text.StringBuilder(sr.ReadToEnd())
                Dim msdoc = New HTMLDocument()
                CType(msdoc, mshtml.IHTMLDocument2).write(buf.ToString())
                Dim element = msdoc.getElementById("link_A_1")
                If (element IsNot Nothing) Then
                    Dim link = CType(element, HTMLDivElement)
                    If (link IsNot Nothing) Then
                        Dim spans = CType(link.getElementsByTagName("span"), IHTMLElementCollection)
                        If (spans.length <> 0) Then
                            Console.WriteLine(CType(spans.item(0), IHTMLElement).innerText)
                        End If
                    End If
                End If
            End Using
        End Using

        Console.ReadLine()
    End Sub
End Module