ITPub博客

首页 > IT职业 > IT图书 > 实例讲解urllib在python2和python3的使用差异

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

IT图书 作者:flyingbunny 时间:2021-09-09 09:41:18 0 删除 编辑

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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/489/viewspace-2806077/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2020-07-23

  • 博文量
    0
  • 访问量
    910