C#多线程爬虫抓取免费代理IP的示例代码
这里用到一个HTML解析辅助类:HtmlAgilityPack,如果没有网上找一个增加到库里,这个插件有很多版本,如果你开发环境是使用VS2005就2.0的类库,VS2010就使用4.0,以此类推..........然后直接创建一个控制台应用,将我下面的代码COPY替换就可以运行,下面就来讲讲我两年前做爬虫经历,当时是给一家公司做,也是用的C#,不过当时遇到一个头痛的问题就是抓的图片有病毒,然后系统挂了几次。所以抓网站图片要注意安全,虽然我这里没涉及到图片,但是还是提醒下看文章的朋友。
classProgram
{
//存放所有抓取的代理
publicstaticListmasterPorxyList=newList();
//代理IP类
publicclassproxy
{
publicstringip;
publicstringport;
publicintspeed;
publicproxy(stringpip,stringpport,intpspeed)
{
this.ip=pip;
this.port=pport;
this.speed=pspeed;
}
}
//抓去处理方法
staticvoidgetProxyList(objectpageIndex)
{
stringurlCombin="http://www.xicidaili.com/wt/"+pageIndex.ToString();
stringcatchHtml=catchProxIpMethord(urlCombin,"UTF8");
HtmlAgilityPack.HtmlDocumentdoc=newHtmlAgilityPack.HtmlDocument();
doc.LoadHtml(catchHtml);
HtmlNodetable=doc.DocumentNode.SelectSingleNode("//div[@id='wrapper']//div[@id='body']/table[1]");
HtmlNodeCollectioncollectiontrs=table.SelectNodes("./tr");
for(inti=0;i0)
{
HtmlNodeitemtdip=(HtmlNode)collectiontds[3];
HtmlNodeitemtdport=(HtmlNode)collectiontds[5];
HtmlNodeitemtdspeed=(HtmlNode)collectiontds[13];
stringip=itemtdip.InnerText.Trim();
stringport=itemtdport.InnerText.Trim();
stringspeed=itemtdspeed.InnerHtml;
intbeginIndex=speed.IndexOf(":",0,speed.Length);
intendIndex=speed.IndexOf("%",0,speed.Length);
intsubSpeed=int.Parse(speed.Substring(beginIndex+1,endIndex-beginIndex-1));
//如果速度展示条的值大于90,表示这个代理速度快。
if(subSpeed>90)
{
proxytemp=newproxy(ip,port,subSpeed);
masterPorxyList.Add(temp);
Console.WriteLine("当前是第:"+masterPorxyList.Count.ToString()+"个代理IP");
}
}
}
}
//抓网页方法
staticstringcatchProxIpMethord(stringurl,stringencoding)
{
stringhtmlStr="";
try
{
if(!String.IsNullOrEmpty(url))
{
WebRequestrequest=WebRequest.Create(url);
WebResponseresponse=request.GetResponse();
Streamdatastream=response.GetResponseStream();
Encodingec=Encoding.Default;
if(encoding=="UTF8")
{
ec=Encoding.UTF8;
}
elseif(encoding=="Default")
{
ec=Encoding.Default;
}
StreamReaderreader=newStreamReader(datastream,ec);
htmlStr=reader.ReadToEnd();
reader.Close();
datastream.Close();
response.Close();
}
}
catch{}
returnhtmlStr;
}
staticvoidMain(string[]args)
{
//多线程同时抓15页
for(inti=1;i<=15;i++)
{
ThreadPool.QueueUserWorkItem(getProxyList,i);
}
Console.Read();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。