asp.net c#采集需要登錄頁面的實現原理及代碼
2024-07-10 12:40:58
供稿:網友
首先說明:代碼片段是從網絡獲取,然后自己修改。我想好的東西應該拿來分享。
實現原理:當我們采集頁面的時候,如果被采集的網站需要登錄才能采集。不管是基于Cookie還是基于Session,我們都會首先發送一個Http請求頭,這個Http請求頭里面就包含了網站需要的Cookie信息。當網站接收到發送過來的Http請求頭時,會從Http請求頭獲取相關的Cookie或者Session信息,然后由程序來處理,決定你是否有權限訪問當前頁面。
好了,原理搞清楚了,就好辦了。我們所要做的僅僅是在采集的時候(或者說HttpWebRequest提交數據的時候),將Cookie信息放入Http請求頭里面就可以了。
在這里我提供2種方法。
第一種,直接將Cookie信息放入HttpWebRequest的CookieContainer里。看代碼:
代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
//設置Cookie,存入Hashtable
Hashtable ht = new Hashtable();
ht.Add("username", "youraccount");
ht.Add("id", "yourid");
this.Collect(ht);
}
public void Collect(Hashtable ht)
{
string content = string.Empty;
string url = "http://www.ibest100.com/需要登錄后才能采集的頁面";
string host = "http://www.ibest100.com";
try
{
//獲取提交的字節
byte[] bs = Encoding.UTF8.GetBytes(content);
//設置提交的相關參數
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json;charset=utf-8";
req.ContentLength = bs.Length;
//將Cookie放入CookieContainer,然后再將CookieContainer添加到HttpWebRequest
CookieContainer cc = new CookieContainer();
cc.Add(new Uri(host), new Cookie("username", ht["username"].ToString()));
cc.Add(new Uri(host), new Cookie("id", ht["id"].ToString()));
req.CookieContainer = cc;
//提交請求數據
Stream reqStream = req.GetRequestStream();
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
//接收返回的頁面,必須的,不能省略
WebResponse wr = req.GetResponse();
System.IO.Stream respStream = wr.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.GetEncoding("utf-8"));
string t = reader.ReadToEnd();
System.Web.HttpContext.Current.Response.Write(t);
wr.Close();
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write("異常在getPostRespone:" + ex.Source + ":" + ex.Message);
}
}
第二種,每次打開采集程序時,需要先到被采集的網站模擬登錄一次,獲取CookieContainer,然后再采集。看代碼:
代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
try
{
CookieContainer cookieContainer = new CookieContainer();
string formatString = "username={0}&password={1}";//***************
string postString = string.Format(formatString, "youradminaccount", "yourpassword");