python使用urllib2实现http代理请求

方法一:
1
#coding=gb2312 2 import urllib2; 3 proxy_handler = urllib2.ProxyHandler({'http':'61.184.192.42:80'}); 4 #此处替换代理IP和端口 5 opener = urllib2.build_opener(proxy_handler) ; 6 f=opener.open('http://1111.ip138.com/ic.asp'); 7 con=f.read(); 8 print con; 9 start=con.find('您的IP是'); 10 end=con.find('</center>'); 11 print con[start:end]; 12 f.close();

 

 方法二:
1
import urllib2 2 3 req = urllib2.Request('http://www.ip138.com/ips138.asp') 4 req.set_proxy('101.201.235.141:8000','http') 5 #req.add_header(key, val)
7
o = urllib2.urlopen(req,data=None) 8 9 res=o.read() 10 print res 11 start=res.find(r'您的IP是') 12 end=res.find('</center>') 13 print res[start:end] 14 o.close()

 

 

urllib2库是http编程中经常使用的一个库,python内置的,直接导入就行。

首行#coding=gb2312原因是IP查询网址(http://1111.ip138.com/ic.asp)使用了gb2312编码;

posted @ 2015-03-24 20:13  Jerory  阅读(402)  评论(0编辑  收藏  举报