会社の文書管理サーバーの中にあるWebページを巡回して処理しないといけないことがあって、でも全社サーバーなのでAPIに触れないので、Webページを読み込んでHTMLを処理しないといけないということがたまにあって、何度か泣きながら同じようなコードを書いているので、スケルトンだけメモっておく。
参照に Microsoft.mshtmlを追加。
<Window x:Class=”Web.MainWindow”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Title=”MainWindow” Height=”344″ Width=”432″>
<Grid>
<WebBrowser Margin=”0,44,0,0″ Name=”webBrowser1″ VerticalAlignment=”Stretch” HorizontalAlignment=”Stretch” LoadCompleted=”webBrowser1_LoadCompleted” />
<Button Content=”Button” Height=”23″ HorizontalAlignment=”Left” Margin=”24,15,0,0″ Name=”button1″ VerticalAlignment=”Top” Width=”75″ Click=”button1_Click” />
</Grid>
</Window>
using System;
using System.Windows;
using System.Windows.Navigation;
using System.Collections;
namespace Web
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
DoScan();
}
string[] url = {
“http://www.yahoo.co.jp”,
“http://uchukamen.com”,
“http://www.google.co.jp”
};
IEnumerator en = null;
private void DoScan()
{
this.button1.IsEnabled = false;
en = url.GetEnumerator();
GoToNextWebPage();
}
private void GoToNextWebPage()
{
if (en.MoveNext())
this.webBrowser1.Source = new Uri((string)en.Current);
else
this.button1.IsEnabled = true;
}
private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
{
DoParse();
GoToNextWebPage();
}
private void DoParse()
{
string text = ((mshtml.HTMLDocument)this.webBrowser1.Document).documentElement.innerHTML;
string innterText = ((mshtml.HTMLDocument)this.webBrowser1.Document).documentElement.innerText;
}
}
}
コメントを残す