继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

doliangzhe2
关注TA
已关注
手记 15
粉丝 3
获赞 49

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

打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP