关键代码:

 private Hashtable hash;//储存代理ip
private WebProxy currentdaili;
private int dailiExecMaxCount; //每个代理执行最大次数
private int currentDailiExecCount; //当前代理执行次数
public Handler2() //构造函数
{
dailiExecMaxCount = ;
currentDailiExecCount = ;
//hash = GetDailiList();
currentdaili = GetOneDaili();
} //http://www.xici.net.co
/// <summary>
/// 获取代理ip返回hashtable
/// KK 2015-04-22
/// </summary>
/// <returns></returns>
private Hashtable GetDailiList()
{
Hashtable result = new Hashtable();
string strUrl = string.Format("http://www.xici.net.co");
string detailContext = GetHtmlByUrl(strUrl);
if (!string.IsNullOrEmpty(detailContext))
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
string strkeyvalue = string.Empty;
try
{
doc.LoadHtml(detailContext);
HtmlNode node = doc.DocumentNode;
HtmlNodeCollection trlist = node.SelectNodes("//table[@id='ip_list']//tr[@class='odd' or @class='']");
foreach (HtmlNode item in trlist)
{
if (item.SelectNodes("td")[].InnerText.ToUpper() == "HTTP")
{
strkeyvalue = item.SelectNodes("td")[].InnerText + ":" + item.SelectNodes("td")[].InnerText;
result.Add(strkeyvalue, strkeyvalue);
}
}
}
catch (Exception ex)
{
webframework.common.logclass.Debug("======取代理ip出错====GetDaili==" + ex.Message);
result = null;
} }
else
{
result = null;
}
return result;
} /// <summary>
/// 从hashtable代理中取任意ip代理
/// </summary>
/// <param name="hash"></param>
/// <returns></returns>
private WebProxy GetOneDaili()
{
try
{
if (hash == null || hash.Count == )
hash = GetDailiList();
if (currentdaili != null && hash.Contains(currentdaili.Address.Authority + ":" + currentdaili.Address.Port))
{
hash.Remove(currentdaili.Address.Authority + ":" + currentdaili.Address.Port);
}
System.Collections.IDictionaryEnumerator enumerator = hash.GetEnumerator(); //随机取代理
Random rd = new Random();
int n = rd.Next(hash.Count);
int intCount = ;
while (enumerator.MoveNext())
{
intCount++;
if (intCount == n)
{
currentdaili = new WebProxy(enumerator.Key.ToString(), true);
break;
}
}
}
catch (Exception ex)
{
webframework.common.logclass.Debug("======从hashtable代理中取任意ip代理出错====GetOneDaili==" + ex.Message);
currentdaili = null;
}
logclass.Debug("======当前代理======" + currentdaili.Address.Authority + ":" + currentdaili.Address.Port );
return currentdaili;
}

使用:

 /// <summary>
/// 发送get请求
/// </summary>
/// <param name="strUrl"></param>
/// <param name="isRetry"></param>
/// <returns></returns>
private string GetHtmlByUrl(string strUrl, bool isRetry = false, WebProxy daili = null)
{
currentDailiExecCount++;
if (currentDailiExecCount > dailiExecMaxCount)
{
logclass.Debug("======当前代理======" + currentdaili.Address.Authority + ":" + currentdaili.Address.Port + "==跑的次数超过了设置的最大次数(" + dailiExecMaxCount.ToString()+")");
}
try
{
HttpWebResponse response = new webframework.common.HttpHelper()
{
URL = string.Format("{0}", strUrl),
//Proxy = daili == null ? currentdaili : daili,
//Proxy = new WebProxy("218.204.140.97:8118", true),
Proxy = daili == null ? (currentDailiExecCount > dailiExecMaxCount ? GetOneDaili() : currentdaili) : daili,
Timeout = * ,
}.CreateGetHttpResponse(); return response.HttpString(Encoding.UTF8);
}
catch (Exception)
{
//重试请求
if (!isRetry)
return GetHtmlByUrl(strUrl, true, GetOneDaili());
else
throw null;
} } /// <summary>
/// 发送post请求
/// </summary>
/// <param name="strUrl"></param>
/// <param name="isRetry"></param>
/// <returns></returns>
private string PostHtmlByUrl(string strUrl, string strPostString, bool isRetry = false, WebProxy daili = null)
{
currentDailiExecCount++;
if (currentDailiExecCount > dailiExecMaxCount)
{
logclass.Debug("======当前代理======" + currentdaili.Address.Authority + ":" + currentdaili.Address.Port + "==跑的次数超过了设置的最大次数(" + dailiExecMaxCount.ToString()+")");
}
try
{
HttpWebResponse response = new HttpHelper()
{
URL = strUrl,
PostString = strPostString,
//Proxy = new WebProxy("218.204.140.97:8118", true),
Proxy = daili == null ? (currentDailiExecCount>dailiExecMaxCount?GetOneDaili(): currentdaili) : daili,
//Proxy = daili == null ? currentdaili : daili,
PostEncoding = Encoding.UTF8,
Timeout = * ,
}.CreatePostHttpResponse(); return response.HttpString(Encoding.UTF8);
}
catch (Exception)
{
//重试请求
if (!isRetry)
return PostHtmlByUrl(strUrl, strPostString, true, GetOneDaili());
else
throw null;
} }

参考资料:

http://www.haolizi.net/example/view_199.html

使用代理(WebProxy)爬虫的更多相关文章

  1. python获取ip代理列表爬虫

    最近练习写爬虫,本来爬几张mm图做测试,可是爬到几十张的时候就会返回403错误,这是被网站服务器发现了,把我给屏蔽了. 因此需要使用代理IP.为了方便以后使用,我打算先写一个自动爬取ip代理的爬虫,正 ...

  2. java爬虫系列第五讲-如何使用代理防止爬虫被屏蔽?

    本文内容 1.分析一下爬虫存在的问题及解决方案 2.webmagic中代理的使用 3.目前市面上一些比较好用的代理服务器 存在的问题 我们在使用爬虫过程中,大多都会遇到这样的问题:突然某一天爬虫爬不到 ...

  3. 免费代理ip爬虫分享

    分享一个某代理网站的免费代理ip的爬虫,直接复制到pycharm运行就可以了. 注意:爬取的代理ip有点坑,因为是免费的所以过期时间很快,可能1分钟后就会失效.并且在scrapy使用这些代理ip还会给 ...

  4. 潭州课堂25班:Ph201805201 爬虫高级 第十三 课 代理池爬虫检测部分 (课堂笔记)

    1,通过爬虫获取代理 ip ,要从多个网站获取,每个网站的前几页2,获取到代理后,开进程,一个继续解析,一个检测代理是否有用 ,引入队列数据共享3,Queue 中存放的是所有的代理,我们要分离出可用的 ...

  5. Python爬虫代理池

    爬虫代理IP池 在公司做分布式深网爬虫,搭建了一套稳定的代理池服务,为上千个爬虫提供有效的代理,保证各个爬虫拿到的都是对应网站有效的代理IP,从而保证爬虫快速稳定的运行,当然在公司做的东西不能开源出来 ...

  6. [python]新手写爬虫v2.5(使用代理的异步爬虫)

    开始 开篇:爬代理ip v2.0(未完待续),实现了获取代理ips,并把这些代理持久化(存在本地).同时使用的是tornado的HTTPClient的库爬取内容. 中篇:开篇主要是获取代理ip:中篇打 ...

  7. 可能是一份没什么用的爬虫代理IP指南

    写在前面 做爬虫的小伙伴一般都绕不过代理IP这个问题. PS:如果还没遇到被封IP的场景,要不就是你量太小人家懒得理你,要不就是人家压根不在乎... 爬虫用户自己是没有能力维护一系列的代理服务器和代理 ...

  8. (转)新手写爬虫v2.5(使用代理的异步爬虫)

    开始 开篇:爬代理ip v2.0(未完待续),实现了获取代理ips,并把这些代理持久化(存在本地).同时使用的是tornado的HTTPClient的库爬取内容. 中篇:开篇主要是获取代理ip:中篇打 ...

  9. 【Python3爬虫】教你怎么利用免费代理搭建代理池

    一.写在前面 有时候你的爬虫刚开始的时候可以正常运行,能够正常的爬取数据,但是过了一会,却出现了一个“403 Forbidden",或者是”您的IP访问频率太高“这样的提示,这就意味着你的I ...

随机推荐

  1. redis 配置应用(摘)

    Redis可以在没有配置文件的情况下通过内置的配置来启动,但是这种启动方式只适用于开发和测试. 合理的配置Redis的方式是提供一个Redis配置文件,这个文件通常叫做redis.conf. redi ...

  2. iOS应用之间跳转

    本篇博文将涉及到以下知识点: app应用跳转的原理解析 如何实现两个app应用之间的跳转 如何实现两个app之间跳转到指定界面 二.应用跳转原理 相信从一个应用跳转到另一个应用大家并不陌生,最常见的莫 ...

  3. Objective-C( 语法二)

     分类(Category):可以给某一个类扩充一些方法(不修改原来类的代码)  作用:在不改变原来类内容基础上,可以为类增加一些方法  使用注意: 1. 只能增加方法,不能增加成员变量 2. 分类方法 ...

  4. Intellij快捷键

  5. 14072202(带IK的Recoil)

    [目标] 带IK的Recoil [思路] 1 继承于USkelControlLimb和UGameSkelCtrl_Recoil 2 效果对比  以这个骨骼为例 Recoil Limb 可见,Recoi ...

  6. OC方法和文件编译

    OC方法和文件编译 一.OC方法 (一)对象方法 (1)对象方法以-开头如 -(void)xx; (2)对象方法只能又对象来调用 (3)对象方法中可以访问当前对象的成员变量 (4)调用格式   [对象 ...

  7. hadoop运行原理之Job运行(三) TaskTracker的启动及初始化

    与JobTracker一样,TaskTracker也有main()方法,然后以线程的方式启动(继承了Runnable接口).main()方法中主要包含两步:一是创建一个TaskTracker对象:二是 ...

  8. Struts2中实现Web项目的初始化工作

    Struts2中实现Web项目的初始化工作 注:通常web系统在启动时需要做一些初始化的工作,比如初始化系统全局变量,加载自定义配置文件,启动定时任务等.  一.在Struts中实现系统的初始化工作 ...

  9. stanford Protege 4.3 ERROR: Bundle org.protege.common 解决方法

    我的java版本是jdk1.8.0_45,安装了protege后打开总显示: ERROR: Bundle org.protege.common [1] Error starting file:/hom ...

  10. springmvc学习第二天

    一.pojo Spring mvc 会按请求参数名和pojo属性名进行自动匹配,自动为该对象填充属性值,并且支持级联属性 表单: <form action="springmvc/tes ...