這個其實不能算是完全意義上的網路扒蟲,只是對某個社交網路進行扒取,然後得到鄰接矩陣,以及相應的頭像等資訊。
主要的步驟:
1,扒取資訊
2,正則匹配
Regex主要參考了:http://deerchao.net/tutorials/regex/regex.htm
扒取資訊中用的是WebClient這個方法相對HttpRequest的HttpResponse更簡潔一些。
痛點是克服網站的認證機制,用的是儲存Cookies的方法。
扒虫部分代碼:
usingSystem;
usingSystem.Net;
usingSystem.Text;
usingSystem.Text.RegularExpressions;
publicclassCrawler
{
publicstaticstringGetCont(stringurl)//扒取頁面
{
stringcookies="_r01_=;depovince=BJ;p=;ap=;t=;societyguester=55a777838c4286ab5f657382dbd25c736;id=;xnsid=";
WebClientWebC=newWebClient();
WebC.Headers.Add("Cookie",cookies);
byte[]WebPa=WebC.DownloadData(url);
stringPageHtml=Encoding.UTF8.GetString(WebPa);
returnPageHtml;
}
publicstaticvoidGetImag(stringImgUrl,stringUserName)//下載小圖片
{
stringimageFileName;
stringimageFilePath;
WebClientmyClient=newWebClient();
Regexregex=newRegex("//w*");
MatchCollectionUsNameMatches=regex.Matches(UserName);
imageFileName=UsNameMatches[0].Value.ToString()+".jpg";
imageFilePath=@"D:/picture/"+imageFileName;
try
{
myClient.DownloadFile(ImgUrl,imageFilePath);
}
catch
{
}
}
}
//Regex部分
usingSystem.Text;
usingSystem.Text.RegularExpressions;
publicclassMyRegex
{
publicstaticstring[]GetAddr(stringPageHtml)
{
string[]PageUrl=newstring[24];
Regexregex=newRegex("http://www..com/profile.do//?portal=//w*&id=//d+(?=/"//stitle=)");
MatchCollectionurlMatches=regex.Matches(PageHtml);
for(inti=0;i<urlMatches.Count;i++)
{
PageUrl[i]=urlMatches[i].Value.ToString();
}
returnPageUrl;
}
publicstaticstring[]GetImgAddr(stringPageHtml)
{
string[]ImgAddr=newstring[24];
Regexregex=newRegex("(?<=stats=/"pf_friend/"//ssrc//=/").*(?=/"//swidth=/"50/"//s/>)");
MatchCollectionImgMatches=regex.Matches(PageHtml);
for(inti=0;i<ImgMatches.Count;i++)
{
ImgAddr[i]=ImgMatches[i].Value.ToString();
}
returnImgAddr;
}
publicstaticstring[]GetUsName(stringPageHtml)
{
string[]UsName=newstring[24];
Regexregex=newRegex("(?<=title=/"查看).*(?=的個人首頁/">//W<img//sstats=/"pf_friend/")");
MatchCollectionUsNameMatches=regex.Matches(PageHtml);
for(inti=0;i<UsNameMatches.Count;i++)
{
UsName[i]=UsNameMatches[i].Value.ToString();
}
returnUsName;
}
}