背景
最近在调用聚合数据的短信API接口,原有的代码是python2,目前我所使用的python全部都在3上(因为mysql接口已经迁移到3),所以稍微爬了一下代码,做了迁移工作
步骤
- 首先要将导入的库做变换
#Python2
import json, urllib
from urllib import urlencode
#迁移至python3
import json,urllib.request
from urllib.parse import urlencode
2.内部代码也要做些更改
#Python2
params = urlencode(params)
if m =="GET":
f = urllib.urlopen("%s?%s" % (url, params)):
f = url.read()
else:
f = urllib.urlopen(url, params):
f = url.read()
content = f.read()
res = json.loads(content)
#迁移至python3
params = urlencode(params)
if m =="GET":
with urllib.request.urlopen("%s?%s" % (url, params)) as url:
f = url.read()
else:
with urllib.request.urlopen(url, params) as url:
f = url.read()
content=f
res = json.loads(content)
参考文献:
https://techoverflow.net/2015/02/08/fixing-importerror-cannot-import-name-urlencode-in-python3/
https://stackoverflow.com/questions/3969726/attributeerror-module-object-has-no-attribute-urlopen
网友评论