实例讲解urllib在python2和python3的使用差异

Urllib是python提供的一个用于操作url的模块, 在python2和python3间是不兼容的,所以实际开发众我们需要为这两个版本分别写一套代码。

在python2中,有urllib库和urllib2库。在python3中,urllib2合并到urllib库中。

以下是python2与python3中常用的关于urllib库的变化:

   1.在python2中使用import urllib2————对应的,在python3中会使用import urllib.request,urllib.error

   2.在python2中使用import urllib————对应的,在python3中会使用import urllib.request,urllib.error,urllib.parse

   3.在python2中使用import urlparse————对应的,在python3中会使用import urllib.parse

   4.在python2中使用urllib2.urlopen————对应的,在python3中会使用urllib.request.urlopen

   5.在python2中使用urllib.urlencode————对应的,在python3中会使用urllib.parse.urlencode

   6.在python2中使用urllib.quote————对应的,在python3中会使用urllib.request.quote

   7.在python2中使用cookielib.CookieJar————对应的,在python3中会使用http.CookieJar

   8.在python2中使用urllib2.Request————对应的,在python3中会使用urllib.request.Request

 

下面我们通过具体实例来说明一下, 榛子云短信(短信验证码平台)的一个发送api:

python2源码:

import urllib
import urllib2
 
class ZhenziSmsClient(object):
	url = "http://sms.zhenzikj.com";
	def __init__(self, appId, appSecret):
		self.appId = appId
		self.appSecret = appSecret
	def send(self, number, message):
		data = {
    	    'appId': self.appId,
		    'appSecret': self.appSecret,
		    'message': message,
		    'number': number
		}
		data = urllib.urlencode(data);
		req = urllib2.Request(self.url+'/sms/send.do', data);
		res_data = urllib2.urlopen(req);
		res = res_data.read();
		return res;

send是发送短信方法,参数number是接收手机号码,message是短信内容

python3源码:

import urllib.request
import urllib.parse
 
class ZhenziSmsClient(object):
	url = "http://sms.zhenzikj.com";
	def __init__(self, appId, appSecret):
		self.appId = appId
		self.appSecret = appSecret
 
	def send(self, number, message):
		data = {
    	    'appId': self.appId,
		    'appSecret': self.appSecret,
		    'message': message,
		    'number': number
		}
		data = urllib.parse.urlencode(data).encode('utf-8');
		req = urllib.request.Request(self.url+'/sms/send.do', data=data);
		res_data = urllib.request.urlopen(req);
		res = res_data.read();
		res = res.decode('utf-8');
		return res;

文章来源: http://smsow.zhenzikj.com/bbs/question/detail/48.html

转载于:https://my.oschina.net/u/3919887/blog/1922466

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值