IE9、Chrome、Firefox などのさまざまなブラウザーを使用してアクセスしたかのように、c# を使用して Web ページの HTML ソースを取得したいと考えています。それを行う方法はありますか?
2 に答える
HTML ソースはさまざまな方法で取得できます。私の好みの方法はHTML Agility Packです
HtmlDocument doc = new HtmlDocument();
doc.Load("http://domain.com/resource/page.html");
doc.Save("file.htm");
.NETのWebClientもうまく機能します。
WebClient myWebClient = new WebClient();
myWebClient.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); // If you need to simulate a specific browser
byte[] myDataBuffer = myWebClient.DownloadData (remoteUri);
string download = Encoding.ASCII.GetString(myDataBuffer);
// This is verbatim from MSDN... unfortunately their example does not dispose
// of myWebClient (it implements IDisposable). You should wrap use of a WebClient
// in a using statement.
http://msdn.microsoft.com/en-us/library/xz398a3f.aspx
あなたが得るHTMLはあなたが得るものです。特定のブラウザーが、それをどうするかを決定します (つまり、サーバーがさまざまなユーザー エージェントに対してさまざまな HTML をレンダリングする場合を除きます)。
(さまざまなブラウザーをシミュレートするために) ユーザー エージェントを明示的に設定する必要がある場合は、次の投稿でその方法を示します。
http://blog.abodit.com/2010/03/a-simple-web-crawler-in-c-using-htmlagilitypack/
(このリンクは、HTML Agility Pack を使用して単純な Web クローラーも実装しています)
私は C# の専門家ではありませんが、URL にアクセスする「ブラウザー」に関係なく html が同じであると仮定すると、System.Net.WebClient (単純な制御のみが必要な場合) または HttpWebRequest (より高度な制御が必要な場合) を使用できます。 )
WebClient の場合は、インスタンスを作成し、その Download* メソッドの 1 つを呼び出すだけです。
var cli = new WebClient();
string data = cli.DownloadString("http://www.stackoverflow.com");