关键代码:

 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. C++学习之:括号匹配与栈的使用

    #include <stack> using std::stack ; 变量定义: stack<T>  stackName ; 成员函数: 成员函数 功能 bool  empt ...

  2. WCF双向通信,心跳

    合肥程序员群:49313181.    合肥实名程序员群:128131462 (不愿透露姓名和信息者勿加入)Q  Q:408365330     E-Mail:egojit@qq.com WCF中双程 ...

  3. eclipse 本地项目提交到远程库以及从远程库中添加项目 ---git

    本地项目提交到远程库 1.右击项目->team->share project 2.选择本地库 从远处库中的项目拉到本地 1.右击项目->import项目

  4. PHP基础示例:用PHP+Mysql编写简易新闻管理系统[转]

    实现目标:使用php和mysql操作函数实现一个新闻信息的发布.浏览.修改和删除操作 实现步骤: 一.创建数据库和表 1.创建数据库和表:newsdb 2.创建表格:news 字段:新闻id,标题,关 ...

  5. Java 并发和多线程(二) 多线程的优点 [转]

    原文:http://tutorials.jenkov.com/java-concurrency/benefits.html 作者:Jakob Jenkov        翻译:古圣昌         ...

  6. redis服务和扩展安装(windows)

    Windows下安装redis和在php中使用phpredis扩展 原文地址:http://m.oschina.net/blog/281058 Junn 发布于 2年前,共有 0 条评论 1.redi ...

  7. 二模 (15)day2

    第一题:Alice和Bob两个人正在玩一个游戏,游戏有很多种任务,难度为p的任务(p是正整数),有1/2p 的概率完成并得到2p−1分,如果完成不了,得0分.一开始每人都是0分,从Alice开始轮流做 ...

  8. [转]SecureCRT连接主机时,无法从键盘输入

    问题: SecureCRT连接主机时,无法从键盘输入 答案: 最近通过超级终端或者SecureCRT连接主机时,都只能读取设备信息,但是无法从键盘输入,进入不了配置状态,后来仔细检查了配置,居然是流控 ...

  9. [转]Linux中设置服务自启动的三种方式

    from:http://www.cnblogs.com/nerxious/archive/2013/01/18/2866548.html 有时候我们需要Linux系统在开机的时候自动加载某些脚本或系统 ...

  10. C# 列主元素(Gauss)消去法 计算一元多次方程组

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...