作者mongsq (有學問的孟孟)
看板C_Sharp
標題Re: [問題] 請問如何c#登入有帳號密碼的網頁 抓網괠…
時間Thu Sep 20 19:11:54 2007
我的做法
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create("
http://LoginUrl");
//上面的網址要自己查一下,通常是登入頁
webReq.CookieContainer = new CookieContainer(); //拿來裝Cookie的東西
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.Method = "POST";
string postString = "username=abc&password=123";
//該post的東西可能要自己查一下,可以用攔截封包的軟體來得知
byte[] postData = Encoding.ASCII.GetBytes(postString)
webReq.ContentLength = postData.Length;
Stream sm = webReq.GetRequestStream();
sm.Write(postData, 0, postData.Length);
sm.Close();
//取得回應
HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
//取得cookie
string cookie = webReq.CookieContainer.GetCookieHeader(webReq.RequestUri);
webResp.Close();
//再來建立你要取得的Request
webReq = (HttpWebRequest)WebRequest.Create("
http://WhatYouWantToGet");
//將剛剛取得的cookie加上去
webReq.Headers.Add("cookie:" + cookie);
//取得回應
webResp = (HttpWebResponse)webReq.GetResponse();
//取得網站資料
Stream stream = webResp.GetResponseStream();
StreamReader sr = new StreamReader(stream, Encoding.Default);
//上面的編碼得自己判斷
String webData = sr.ReadToEnd();
webResp.Close();
之前在做的時候還有遇到一個問題
在取得cookie的時候伺服器會傳回417錯誤
如果有發生的話
在取得cookie之前把ServicePointManager.Expect100Continue設成false就行了
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.142.138.27
推 liptonbin:謝謝你喔 不過還是會少網頁原始碼 = = 09/21 13:49
→ conanist:這個方法是幫助你通過login網頁這樣你才有權限進入爬資料 06/18 11:15
→ conanist:至於匿名存取爬網址 A Simple Crawler Using C# Sockets 06/18 11:19