HttpWebRequest抓取图片
public static bool downloadFile(string url, string savePath, ref Exception ex,ref int fileSize)
{
HttpWebRequest req=null;
HttpWebResponse res=null;
System.IO.Stream stream = null;
bool result = false;
System.GC.Collect();
try
{
req = HttpWebRequest.Create(url) as System.Net.HttpWebRequest;
req.CookieContainer = new CookieContainer();
req.AllowAutoRedirect = true;
req.KeepAlive = false;
req.Timeout = 60 * 1000;
req.ServicePoint.ConnectionLeaseTimeout = 2 * 60 * 1000;
// req.ServicePoint.ConnectionLimit = int.MaxValue;
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1";
req.Headers.Add("Accept-Language", "en-us,en;q=0.5");
req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
req.Headers.Add("Accept-Encoding", "gzip, deflate");
res = req.GetResponse() as System.Net.HttpWebResponse;
stream = res.GetResponseStream();
byte[] buffer = new byte[1 * 1024];
int bytesProcessed = 0;
System.IO.FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write);
int bytesRead;
do
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, bytesRead);
bytesProcessed += bytesRead;
}
while (bytesRead > 0);
fs.Flush();
fs.Close();
result = true;
fileSize = bytesProcessed;
}
catch (Exception exception)
{
ex = exception;
}
finally
{
if (stream != null)
{
stream.Close(); stream.Dispose();
}
if (req != null)
{
req.Abort();
req = null;
}
if (res != null)
{
res.Close();
res = null;
}
}
return result;
}我自己搞了个小爬虫软件玩玩,抓取网站的图片,主要代码如上。
一开始抓取的时候是没问题的,但是抓取到一定数量的时候(1000到3000张图片之间),抓取速度越来越慢,抓取花费的时候,一直不断攀升,最后甚至长达几分钟,而且多数是超时失败了。
我把那些失败的图片地址拷贝到浏览器直接访问,大部分是没问题。请教各位大虾,有什么优化方案吗?哦,对了,我是用多线程的,不论我开多少线程(一般在20个左右)在抓取,到了一定时候,都会出现这情况。
...全文
相关推荐
C# 猫扑图片抓取器
程序通过httpwebrequest类和正则表达式获得网页图片.并能依次获得该内容的顺推图片
picturebox加载图片的三种方法与网站验证码的抓取
主要介绍了picturebox加载图片的三种方法与网站验证码的抓取,需要的朋友可以参考下
C#爬虫蜘蛛程序(图片抓取).rar
一个C#写的图片抓取程序,稍加修改同样适用于网页内容获取!因为是初学者,写的不好多多见谅!
C#写的网页抓取软件源码
很好用的,用C#写的网页内容抓取工具,很完整的vs2008项目
C#爬图软件-------附赠源码!
使用C#去,爬取任意html网页里面所有.png .jpg.gif 的所有图片。并下载到指定文件夹里面。


