實現HTTP內容的抓取

來源:互聯網
上載者:User
前段時間做了一個網頁爬蟲,初次接觸,收穫了很多知識。其中關於HTTP協議的內容,記述如下:

        RFC2616中主要描述了HTTP 1.1協議。下面的描述沒有實現其各個方面的內容,只提出了一種能夠完成所有HTTP網頁抓取的最小實現(不能夠抓取HTTPS)。

        1、首先提交一個URL地址,分為普通的GET網頁擷取,POST的資料提交兩種基本模式。

建立HttpWebReques執行個體,其中uri是網頁的URL的地址:
   HttpWebRequest webrequest = (HttpWebRequest) WebRequest.Create(uri);

KeepAlive表示HTTP的串連是長串連:
   webrequest.KeepAlive = true;

如果需要,添加引用地址,主要用於防止其他網站的串連引用,比如登陸時,經常需要驗證:
   if(referer!=null)
   {
    webrequest.Referer=referer;
   }

選擇資料的提交方式,有GET、POST兩種方式,HEAD不常用:
   switch(RequestMethod)
   {
    case 1:
     webrequest.Method="GET";
     break;
    case 2:
     webrequest.Method="POST";
     break;
    case 3:
     webrequest.Method="HEAD";
     break;
    default:
     webrequest.Method="GET";
     break;
   }

設定User-Agent,經常遇到,在某些網站中,做了限制,User-Agent為空白,則不能訪問:
   webrequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50215; fqSpider)";

添加其他的HTTP的Header資訊,collHeader是一個NameValue的Collection:
   if(collHeader!=null&&collHeader.Count>0)
   {
    int iCount = collHeader.Count;
    string key;
    string keyvalue;
 
    for (int i=0; i < iCount; i++)
    {
     key = collHeader.Keys[i];
     keyvalue = collHeader[i];
     webrequest.Headers.Add(key, keyvalue);
    }
   }

設定Content-Type的內容,如果為POST,設定成application/x-www-form-urlencoded,如果是Get設定成text/html:
   if(webrequest.Method=="POST")
   {
    webrequest.ContentType="application/x-www-form-urlencoded";
   }
   else
   {
    webrequest.ContentType = "text/html";
   }
   
 
設定Proxy 伺服器地址和連接埠:
   if ((ProxyServer!=null) &&(ProxyServer.Length > 0))
   {
    webrequest.Proxy = new
     WebProxy(ProxyServer,ProxyPort);
   }

設定是否允許自動轉移:
   webrequest.AllowAutoRedirect = true;

設定基本的登陸認證 :
   if (NwCred)
   {
    CredentialCache wrCache =
     new CredentialCache();
    wrCache.Add(new Uri(uri),"Basic",
     new NetworkCredential(UserName,UserPwd));
    webrequest.Credentials = wrCache;
   }  

設定Request的Cookie容器:
   webrequest.CookieContainer=Cookies;

設定POST資料:
   byte[] bytes = Encoding.ASCII.GetBytes(RequestData);
   webrequest.ContentLength=bytes.Length;
 
   Stream oStreamOut = webrequest.GetRequestStream();
   oStreamOut.Write(bytes,0,bytes.Length);
   oStreamOut.Close();

上面籠統的介紹,重新組合一下,可以實現GetText和GetBinary兩種請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.