Javascript External Library

2022-10-05

Microsoft.Web.WebView2 で Web スクレイピング

はじめに

Microsoft Internet Explorer もなくなり、Microsoft Edge も Chromium になって世の中が Chromium 一色となりました。Wpf を使ってWeb Browser を作るときは System.Windows.Controls.WebBrowser でしたが、これは内部がIE7というとんでもない骨董品でした。Wpf で Chromium は扱えなくもないですが、微妙に扱いにくいのでどうしたものかと思っていたら Microsoft が Microsoft.Web.WebView2 を出してくれたのでこれをちょっと触ってみることにします。

XAMLに埋め込む

XAMLに埋め込むのはこんな感じです。
  1. <UserControl x:Class="UserControls.WebBrowser"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  5. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  6. xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
  7. mc:Ignorable="d"
  8. d:DesignHeight="450" d:DesignWidth="800">
  9. <Grid>
  10. <wv2:WebView2
  11. x:Name="WebViewer" />
  12. </Grid>
  13. </UserControl>
Microsoft.Web.WebView2 は Nuget から拾ってきます。


URLで画面遷移する

アドレスバーの入力など任意のWebページに遷移するのは Source Property を指定します。
  1. using Microsoft.Web.WebView2.Wpf;
  2. using System;
  3. using System.IO;
  4. using System.Windows;
  5. using System.Windows.Controls;
  6. namespace UserControls.WebBrowser;
  7. public partial class WebBrowser : UserControl
  8. {
  9. public WebBrowser()
  10. {
  11. InitializeComponent();
  12. WebViewer..Source = new Uri(@"https://www.lutheta.jp/");
  13. }
  14. }

Responseを拾う

Response を拾うには WebResourceResponseReceived を拾えばいいです。ただ、これは Microsoft.Web.WebView2.Wpf.WebView2 の CoreWebView2 Property の Microsoft.Web.WebView2.Core.CoreWebView2 にあるので注意が必要です。
  1. using Microsoft.Web.WebView2.Wpf;
  2. using System;
  3. using System.IO;
  4. using System.Windows;
  5. using System.Windows.Controls;
  6. namespace UserControls.WebBrowser;
  7. public partial class WebBrowser : UserControl
  8. {
  9. public WebBrowser()
  10. {
  11. InitializeComponent();
  12.  
  13. WebViewer.CoreWebView2InitializationCompleted += (sender, e) =>
  14. {
  15. if (sender != null)
  16. ((WebView2)sender).CoreWebView2.WebResourceResponseReceived += async (sender, e) =>
  17. {
  18. }
  19. };
  20. }
  21. }
CoreWebView2 は Component の Initialize 時には Null なので CoreWebView2InitializationCompleted Event で WebResourceResponseReceived Event をセットするようにします。

これを利用して

とりあえず MarineTraffic から航跡を抽出するアプリを作ってみました。

MarinTraffic

なかなか応用幅が広がりそうな感じでです。

0 件のコメント:

コメントを投稿