实例讲解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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容