使用代理(WebProxy)爬虫
关键代码:
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)爬虫的更多相关文章
- python获取ip代理列表爬虫
最近练习写爬虫,本来爬几张mm图做测试,可是爬到几十张的时候就会返回403错误,这是被网站服务器发现了,把我给屏蔽了. 因此需要使用代理IP.为了方便以后使用,我打算先写一个自动爬取ip代理的爬虫,正 ...
- java爬虫系列第五讲-如何使用代理防止爬虫被屏蔽?
本文内容 1.分析一下爬虫存在的问题及解决方案 2.webmagic中代理的使用 3.目前市面上一些比较好用的代理服务器 存在的问题 我们在使用爬虫过程中,大多都会遇到这样的问题:突然某一天爬虫爬不到 ...
- 免费代理ip爬虫分享
分享一个某代理网站的免费代理ip的爬虫,直接复制到pycharm运行就可以了. 注意:爬取的代理ip有点坑,因为是免费的所以过期时间很快,可能1分钟后就会失效.并且在scrapy使用这些代理ip还会给 ...
- 潭州课堂25班:Ph201805201 爬虫高级 第十三 课 代理池爬虫检测部分 (课堂笔记)
1,通过爬虫获取代理 ip ,要从多个网站获取,每个网站的前几页2,获取到代理后,开进程,一个继续解析,一个检测代理是否有用 ,引入队列数据共享3,Queue 中存放的是所有的代理,我们要分离出可用的 ...
- Python爬虫代理池
爬虫代理IP池 在公司做分布式深网爬虫,搭建了一套稳定的代理池服务,为上千个爬虫提供有效的代理,保证各个爬虫拿到的都是对应网站有效的代理IP,从而保证爬虫快速稳定的运行,当然在公司做的东西不能开源出来 ...
- [python]新手写爬虫v2.5(使用代理的异步爬虫)
开始 开篇:爬代理ip v2.0(未完待续),实现了获取代理ips,并把这些代理持久化(存在本地).同时使用的是tornado的HTTPClient的库爬取内容. 中篇:开篇主要是获取代理ip:中篇打 ...
- 可能是一份没什么用的爬虫代理IP指南
写在前面 做爬虫的小伙伴一般都绕不过代理IP这个问题. PS:如果还没遇到被封IP的场景,要不就是你量太小人家懒得理你,要不就是人家压根不在乎... 爬虫用户自己是没有能力维护一系列的代理服务器和代理 ...
- (转)新手写爬虫v2.5(使用代理的异步爬虫)
开始 开篇:爬代理ip v2.0(未完待续),实现了获取代理ips,并把这些代理持久化(存在本地).同时使用的是tornado的HTTPClient的库爬取内容. 中篇:开篇主要是获取代理ip:中篇打 ...
- 【Python3爬虫】教你怎么利用免费代理搭建代理池
一.写在前面 有时候你的爬虫刚开始的时候可以正常运行,能够正常的爬取数据,但是过了一会,却出现了一个“403 Forbidden",或者是”您的IP访问频率太高“这样的提示,这就意味着你的I ...
随机推荐
- Spirng中Mongodb中write-concern的解释
Spring在插入数据库时没有返回状态配置:write-concern获取异常<beans xmlns="http://www.springframework.org/schema/b ...
- MongoDB:实体对象(javabean)转DBObject
代码仅供练习(反射,泛型): package utils; import java.lang.reflect.Field; import com.mongodb.BasicDBObject; impo ...
- PHP自动发邮件
自动发邮件 使用了这个类http://bbs.php100.com/read-htm-tid-121431.html 因他用的php版本较老,用到了函数ereg_replace() 和 ereg() ...
- Rotate Image [LeetCode]
You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). ...
- 三角形及选中取消按钮的css代码
1.三角形: 1.用传统的方式: .triangle{ background:blue transparent transparent transparent; border-width:100px ...
- 教你看懂GERBER中的钻孔(.txt)文件
PCB在制作的时候也会导出相应钻孔的坐标位置,但是发现网上很少有关于这方面的资料,而一些项目中,可能就会用到钻孔的坐标信息,今天就抛下砖. M48 ;Layer_Color=9474304 % 图层 ...
- Python的平凡之路(4)
一.迭代器&生成器 生成器定义: 通过列表生成式,我们可以直接创建一个列表.但是,受到内存限制,列表容量肯定是有限的.而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅 ...
- Android 开源组件 ----- Android LoopView无限自动轮转控件
Android 开源组件 ----- Android LoopView无限自动轮转控件 2015-12-28 15:26 by 杰瑞教育, 32 阅读, 0 评论, 收藏, 编辑 一.组件介绍 App ...
- C#中的IntPtr类型
本文转自:http://zhidao.baidu.com/question/22825956.html 问: c#中无法将类型“int”隐式转换为“System.IntPtr” 这个是我引用了一个ap ...
- QT中给各控件增加背景图片(可缩放可旋转)的几种方法
http://blog.csdn.net/liukang325/article/details/44832397 1. 给QPushButton 增加背景图片:背景图片可根据Button大小自由缩放. ...