標籤:
1、有些網站訪問速度慢,而且這個網站的串連數(比如全球內衣,另外對於女生各種什麼內衣不懂的也可以上去查看瞭解哈),因為沒有即時的關閉,造成抓取頁面資料的時候逾時也嚴重。
解決:把相應的HttpWebResponse.Close(), HttpWebRequest.Abort(); 以及HttpWebRequest.KeepAlive=false,還有吧逾時時間設定長一點, 之後連線逾時的幾率就貶低了。還有直接c盤的host檔案的網域名稱直接指向某個IP,減少去dns伺服器尋找的時間
2、抓中國供應商的時候開了多線程跑的太快,幾十條就出現拉動類的驗證碼,這個只能降低頻率。
下面是封裝請求的類庫
public static string getRequest(string url, string charset = "utf-8")
{
HttpWebRequest myreq = null;
HttpWebResponse myres = null;
StreamReader reader = null;
Stream stream = null;
string result = "";
string code = charset; //charset.ToLower()
//code = "utf-8";
try
{
myreq = (HttpWebRequest)WebRequest.Create(url);
myreq.Timeout = 20000;
myreq.Method = "GET";
myreq.KeepAlive = false;
myreq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
//myreq.UserAgent = "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)";
myreq.Headers.Add("content", "text/html; charset=" + code);
//myreq.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
myreq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";
myreq.KeepAlive = true;
myres = (HttpWebResponse)myreq.GetResponse();
stream = myres.GetResponseStream();
reader = new StreamReader(stream, System.Text.Encoding.GetEncoding(code));
result = reader.ReadToEnd();
reader.Close();
reader.Dispose();
stream.Close();
stream.Dispose();
}
catch
{ }
finally
{
if (myreq != null)
{
myres.Close();
}
if (myreq != null)
{
myreq.Abort();
}
}
return result;
}
HttpWebRequest抓資料遇到的問題