實例講解urllib在python2和python3的使用差異

Urllib是python提供的一個用于操作url的模塊, 在python2和python3間是不兼容的,所以實際開發(fā)眾我們需要為這兩個版本分別寫一套代碼。

在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


下面我們通過具體實例來說明一下, 榛子云短信(短信驗證碼平臺)的一個發(fā)送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是發(fā)送短信方法,參數(shù)number是接收手機號碼,message是短信內(nèi)容

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

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容