请看这个线程:
在这个线程中,我们回答了同样的问题do...while
。但是呢foreach
?这意味着我们如何使用另一个代理(另一个整数) 重试其中的try
语句:try/catch
foreach
proxy_line_num
foreach (string link_1 in links_with_kid)
{
try
{
getData = "";
req = (HttpWebRequest)WebRequest.Create(link_1);
req.Method = "GET";
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:19.0) Gecko/20100101 Firefox/19.0";
req.ContentType = "text/html; charset=utf-8";
req.Referer = "http://www.example.com/";
req.KeepAlive = true;
req.Timeout = 25000;
if (useproxy)
{
string[] Ok_ip_port_ar = list_lines_GPL[proxy_line_num].Split(':');
proxy_line_num++;
if (proxy_line_num == list_lines_GPL.Count)
{
proxy_line_num = 0;
}
proxy = new WebProxy(Ok_ip_port_ar[0], int.Parse(Ok_ip_port_ar[1]));
}
req.Proxy = proxy;
req.CookieContainer = cookieJar1;
res = (HttpWebResponse)req.GetResponse();
Stream = res.GetResponseStream();
reader = new StreamReader(Stream);
reader_str = reader.ReadToEnd();
htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(reader_str);
var images = from image in htmlDoc.DocumentNode.Descendants("img")
select image;
string address = string.Empty;
foreach (var image in images)
{
if (image.Attributes["src"] != null)
{
string[] address_ar = image.Attributes["src"].Value.Split('/');
string address_ar_last = address_ar[address_ar.Length - 1];
char[] address_ar_last_char = address_ar_last.ToCharArray();
if (address_ar_last_char.Length == 8
&&
Char.IsUpper(address_ar_last_char[0])
&&
Char.IsUpper(address_ar_last_char[1])
&&
Char.IsUpper(address_ar_last_char[2])
&&
Char.IsUpper(address_ar_last_char[3]))
{
address = image.Attributes["src"].Value;
string localFilename = @"c:\images-from-istgah\" + address_ar_last;
using (WebClient client = new WebClient())
{
client.DownloadFile(address, localFilename);
}
}
}
}
}
catch (Exception ex)
{
}
reader.Close();
Stream.Close();
res.Close();
}