C#开发中,一些需要实现抓取某个网站网页内容的需求,但现在很多网站都有单位时间内访问次数的限制。为了在短时间内抓取到更多我们想要的网页内容,这时我们就需要使用代理来实现了。C#来实现IP代理抓取是非常容易实现的,只需要通过WebRequest的Proxy属性来实现,以下为具体实现方法:
private static string DownLoadHtml(string url, int timeout = 30, bool enableProxy = false)
{
try
{
string html = "";
var myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "GET";
myRequest.Timeout = 1000 * timeout;
myRequest.AllowAutoRedirect = true;
if (enableProxy)
{
//如果启用WEBPROXY代理
var webProxy = new WebProxy("37.239.46.18", 80);
myRequest.Proxy = webProxy;
}
var myResponse = (HttpWebResponse)myRequest.GetResponse();
using (var sr = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding((myResponse.CharacterSet))))
{
html = sr.ReadToEnd();
myResponse.Close();
}
return html;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
该方法有三个参数,url为目标页面,timeout为抓取网页的超时时间,enableProxy为是否启用代理。如果成功执行,则返回抓取到的目标页面的源代码。
需要注意的是:在使用此方法之前,你得找到可用的IP(包括主机和端口,如本例中的主机为:37.239.46.18,端口为:80)。
版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。
发表评论
登录用户才能发表评论, 请 登 录 或者 注册