一个利用urllib2模块编写的下载器,虽然有了requests模块,但是毕竟标准库

 import urllib2,random

 class strong_down():
def __init__(self):
#ip_list和agent_list可以自己写到config文件中,然后读出来
      self.proxy_ip_list = ['122.224.227.202:3128',
'182.254.220.21:3128',
'123.7.115.141:9797',
'183.61.236.54:3128',
'124.88.67.31:843',
'120.24.73.165:3128']
self.user_agent_list = ["Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"
]
self.proxy_ip_num = len(self.proxy_ip_list)
self.user_agent_num = len(self.user_agent_list) def proxy_down(self,url,time_out=5,num_retries=3):
proxy_ip = self.proxy_ip_list[random.randint(0,self.proxy_ip_num-1)]
user_agent = self.user_agent_list[random.randint(0,self.user_agent_num-1)]
proxy_handler = urllib2.ProxyHandler({'http':proxy_ip})
opener = urllib2.build_opener(proxy_handler)
request = urllib2.Request(url,headers={'User-Agent':user_agent})
#print request.headers
try:
response = opener.open(request,timeout=time_out)
html = response.read()
if html == None:print 'none'
return html
except urllib2.URLError, e:
if hasattr(e,"code"):
print '',e.code,e.reason
if hasattr(e,"reason"):
print '',e.reason
if num_retries>1:
return self.proxy_down(url,time_out,num_retries-1)
except Exception as e:
print 'error:',e
if num_retries>0:
print 'proxy try...'
return self.proxy_down(url,time_out,num_retries-1)
else:
print u'代理也没diao用'
return None def down(self,url,time_out=5,num_retries=3):
user_agent = self.user_agent_list[random.randint(0,self.user_agent_num-1)]
request = urllib2.Request(url,headers={'User-Agent':user_agent})
try:
response = urllib2.urlopen(request,timeout=time_out)
html = response.read()
return html
except urllib2.URLError, e:
if hasattr(e,"code"):
print '', e.code,e.reason,e.msg
if hasattr(e,"reason"):
print '', e.reason
if num_retries>0:
print 'try...'
return self.down(url,time_out,num_retries-1)
except Exception as e:
print 'error:',e
if num_retries>0:
print 'try...'
return self.down(url,time_out,num_retries-1) #代理
if num_retries <=0:
return self.proxy_down(url,time_out,num_retries=3)

Python2 基于urllib2 的HTTP请求类的更多相关文章

  1. 【PHPsocket编程专题(实战篇③)】构建基于socket的HTTP请求类

    该代码是两年前写的,现在看起来有点渣了,仅仅是提供一个思路,现在做一些Api开发的时候官方会有一些SDK,这些SDK其实原理都是通过socket来通讯的,其实我个人主张用curl更方便,当然前提是你的 ...

  2. 基于Volley,Gson封装支持JWT无状态安全验证和数据防篡改的GsonRequest网络请求类

    这段时间做新的Android项目的client和和REST API通讯框架架构设计.使用了非常多新技术,终于的方案也相当简洁优雅.client仅仅须要传Java对象,server端返回json字符串, ...

  3. 基于socket实现http请求

    异步非阻塞模块原理 # 基于socket实现http请求 import socket # 多路IO复用模块 import select socket_list= [] url_list = [&quo ...

  4. 一个linux下简单的纯C++实现Http请求类(GET,POST,上传,下载)

    目录 一个linux下简单的纯C++实现Http请求类(GET,POST,上传,下载) Http协议简述 HttpRequest类设计 请求部分 接收部分 关于上传和下载 Cpp实现 关于源码中的Lo ...

  5. 一个比较强大的HTTP请求类,支持文本参数和文件参数。

    一个 http 请求类 ,支持文件上传,从淘宝 top sdk 里面扣出来的,蛮好用的,做个记录而已. 调用代码: Dictionary<string, string> textParas ...

  6. 并发编程概述 委托(delegate) 事件(event) .net core 2.0 event bus 一个简单的基于内存事件总线实现 .net core 基于NPOI 的excel导出类,支持自定义导出哪些字段 基于Ace Admin 的菜单栏实现 第五节:SignalR大杂烩(与MVC融合、全局的几个配置、跨域的应用、C/S程序充当Client和Server)

    并发编程概述   前言 说实话,在我软件开发的头两年几乎不考虑并发编程,请求与响应把业务逻辑尽快完成一个星期的任务能两天完成绝不拖三天(剩下时间各种浪),根本不会考虑性能问题(能接受范围内).但随着工 ...

  7. .NetCore简单封装基于IHttpClientFactory的HttpClient请求

    IHttpClientFactory是什么?为什么出现了IHttpClientFactory 一.IHttpClientFactory是什么? IHttpClientFactory是.netcore2 ...

  8. [安卓] 12、开源一个基于SurfaceView的飞行射击类小游戏

    前言  这款安卓小游戏是基于SurfaceView的飞行射击类游戏,采用Java来写,没有采用游戏引擎,注释详细,条理比较清晰,适合初学者了解游戏状态转化自动机和一些继承与封装的技巧. 效果展示    ...

  9. python urllib2 发起http请求post

    使用urllib2发起post请求 def GetCsspToken(): data = json.dumps({"userName":"wenbin", &q ...

随机推荐

  1. Android AES加密算法,现在实际上

    昨天,老板让我来看看android加密算法.于是在网上找了找,发现AES加密算法.(当然,MD5,BASE64什么http://snowolf.iteye.com/blog/379860这篇文章列举了 ...

  2. PHP中生成验证码

    //生成图片$im = imagecreatetruecolor(100,30);//生成颜色,当第一次调用生成颜色的方法,是生成背景颜色,默认是黑色//如果想自定义背景颜色,用到imagefill函 ...

  3. C# 中参数验证方式

    C# 中参数验证方式 一般在写方法的时候,第一步就是进行参数验证,这也体现了编码者的细心和缜密,但是在很多时候这个过程很枯燥和乏味,比如在拿到一个API设计文档的时候,通常会规定类型参数是否允许为空, ...

  4. C#版考题

    某软件大赛C#版考题整理——[单选题]   一.单选题(10小题共20.0分) 1. 以下JavaScript代码的正确输出结果是:(). 1 2 3 4 5 6 7 8 9 <script t ...

  5. iOS基础 - 触摸事件&手势识别

    ================================================================== 一.触摸事件&手势识别 1> 4个触摸事件,针对视图 ...

  6. C++中文件的操作

    #include <iostream> #include <fstream> using namespace std; int main() { char s[27],m[27 ...

  7. C#.Net获取Mac等PC信息

    using System.Management; using System.Net; public class PCInfoHelper { /// <summary> /// 操作系统的 ...

  8. [转]How WebKit Loads a Web Page

    ref:https://www.webkit.org/blog/1188/how-webkit-loads-a-web-page/ Before WebKit can render a web pag ...

  9. ASP.NET MVC企业开发的基本环境

    ASP.NET MVC企业开发的基本环境[资源服务器概念] 学完了ASP.NET MVC4 IN ACTION 六波以后 企业开发演习 标签:AaronYang  茗洋  EasyUI1.3.4   ...

  10. CSS3 3D笨蛋教程

    英文原文An Introduction to CSS 3-D Transforms 爱因斯坦说所有概念都必须介绍给儿童们,若他们无法了解,这些理论就毫无价值. 透视 一个元素需要一个透视点才能激活3D ...