C# で Web ページにログインしてそのコンテンツを取得するにはどうすればよいですか?
7 に答える
それは、ログインに必要なものによって異なります。Web クライアントを使用して、ログイン資格情報をサーバーのログイン ページに送信できます (GET または POST のいずれかの方法が必要です)。Cookie を処理する Web クライアントを取得する方法があるため、ログイン情報をサーバーに POST し、同じ Web クライアントで必要なページを要求し、そのページで必要なことを行うことができます。
System.Net.WebClient
またはより高度な要件については、 を参照してくださいSystem.Net.HttpWebRequest/System.Net.HttpWebResponse
。
これらを実際に適用する場合: スクレイピングする各ページの html ソースを調べて、期待されている Http リクエストを正確に把握する必要があります。
string postData = "userid=ducon";
postData += "&username=camarche" ;
byte[] data = Encoding.ASCII.GetBytes(postData);
WebRequest req = WebRequest.Create(
URL);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("iso-8859-1"));
string coco = reader.ReadToEnd();
「ログイン」とは?
サブフォルダーが OS レベルで保護されていて、そこに移動したときにブラウザーがログイン ダイアログを表示する場合は、HttpWebRequest で Credentials プロパティを設定する必要があります。
Web サイトに独自の Cookie ベースのメンバーシップ/ログイン システムがある場合、HttpWebRequest を使用してログイン フォームに最初に応答する必要があります。
リクエストを自分で作成する代わりに、WebClient オブジェクトでビルドを使用できます。
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username", "password");
string url = "http://foo.com";
try
{
using (Stream stream = wc.OpenRead(new Uri(url)))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
catch (WebException e)
{
//Error handeling
}
WebClientクラスを使用します。
Dim Html As String
Using Client As New System.Net.WebClient()
Html = Client.DownloadString("http://www.google.com")
End Using
これを試して:
public string GetContent(string url)
{
using (System.Net.WebClient client =new System.Net.WebClient())
{
return client.DownloadString(url);
}
}