我们在使用爬虫ip在请求网站时,经常会遇到失败的情况,如果排除爬虫ip方面的问题,那么可能就是自己写的爬虫代码问题了。优秀的程序员会让程序简洁实用,而且随时可以增加工作量随时增加代码,那么在爬虫中使用C#语言应该怎么写?下面的代码可以看看:
string targetUrl = "http://jshk.com.cn";
string proxyIp = "219.151.125.106";
string proxyPort = "31615";
string authKey = "895314XY";
string password = "24D6YB309ZCB";
WebProxy proxy = new WebProxy(string.Format("{0}:{1}", proxyIp, proxyPort), true);
proxy.Credentials = new NetworkCredential(authKey, password);
ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create(targetUrl) as HttpWebRequest;
request.AllowAutoRedirect = true;
request.KeepAlive = true;
request.Method = "GET";
request.Proxy = proxy;
request.Timeout = 10000;
request.ServicePoint.ConnectionLimit = 16;
using (var resp = request.GetResponse() as HttpWebResponse)
using (var reader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8)){
string htmlStr = reader.ReadToEnd();
}
C#语言异常处理
在C#中有很多不同类型的异常可能被发生,关于catch()有三种形式,可以处理不同级别的异常。
第一种 一般异常处理
try
{
}
catch
{
//一般异常处理
}
能接受任何异常,但不能确认引起异常的类型。可对可能发生的异常进行普通处理和清理。
第二种 特定异常处理
try
}
catch(Exception)
{
//特定异常处理
}
把一个异常类的名称作为参数,匹配该指定类或派生自它的异常类的异常。
第三种 带对象的特定异常处理
try
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
可提供关于异常的多种异常信息,匹配指定的异常或派生自它的异常类的异常。通过异常实例,可得到异常的详细信息。
try
}
catch (Exception ex)
{
//特定异常处理
throw new Exception(ex.Message);
}
finally {
//出现异常后的处理机制
}
这里需要特别说明下,关于finally中的代码,不管异常是否被捕获,它都会被执行。