HttpWebRequest抓取图片

chengwangtianxia chengwangtianxia 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
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个左右)在抓取,到了一定时候,都会出现这情况。
...全文
评论 14
收藏 已收藏
分享
返回顶部
chengwangtianxia
.NET社区 62,273 成员 668,968 内容