为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Python

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

点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消