實現(xiàn)HTTP內(nèi)容的抓取
前段時間做了一個網(wǎng)頁爬蟲,初次接觸,收獲了很多知識。其中關(guān)于HTTP協(xié)議的內(nèi)容,記述如下:
RFC2616中主要描述了HTTP 1.1協(xié)議。下面的描述沒有實現(xiàn)其各個方面的內(nèi)容,只提出了一種能夠完成所有HTTP網(wǎng)頁抓取的最小實現(xiàn)(不能夠抓取HTTPS)。
1、首先提交一個URL地址,分為普通的GET網(wǎng)頁獲取,POST的數(shù)據(jù)提交兩種基本模式。
建立HttpWebReques實例,其中uri是網(wǎng)頁的URL的地址:
HttpWebRequest webrequest = (HttpWebRequest) WebRequest.Create(uri);
KeepAlive表示HTTP的連接是長連接:
webrequest.KeepAlive = true;
如果需要,添加引用地址,主要用于防止其他網(wǎng)站的連接引用,比如登陸時,經(jīng)常需要驗證:
if(referer!=null)
{
webrequest.Referer=referer;
}
選擇數(shù)據(jù)的提交方式,有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;
}
設(shè)置User-Agent,經(jīng)常遇到,在某些網(wǎng)站中,做了限制,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);
}
}
設(shè)置Content-Type的內(nèi)容,如果為POST,設(shè)置成application/x-www-form-urlencoded,如果是Get設(shè)置成text/html:
if(webrequest.Method=="POST")
{
webrequest.ContentType="application/x-www-form-urlencoded";
}
else
{
webrequest.ContentType = "text/html";
}
設(shè)置代理服務(wù)器地址和端口:
if ((ProxyServer!=null) &&(ProxyServer.Length > 0))
{
webrequest.Proxy = new
WebProxy(ProxyServer,ProxyPort);
}
設(shè)置是否允許自動轉(zhuǎn)移:
webrequest.AllowAutoRedirect = true;
設(shè)置基本的登陸認證 :
if (NwCred)
{
CredentialCache wrCache =
new CredentialCache();
wrCache.Add(new Uri(uri),"Basic",
new NetworkCredential(UserName,UserPwd));
webrequest.Credentials = wrCache;
}
設(shè)置Request的Cookie容器:
webrequest.CookieContainer=Cookies;
設(shè)置POST數(shù)據(jù):
byte[] bytes = Encoding.ASCII.GetBytes(RequestData);
webrequest.ContentLength=bytes.Length;
Stream oStreamOut = webrequest.GetRequestStream();
oStreamOut.Write(bytes,0,bytes.Length);
oStreamOut.Close();