Python3调用阿里云接口,重新方法,解决ModuleNotFoundError: No module named 'urllib2'

1.使用官方给的Python3运行不了,得改

以下是官方的python接口样品,运行时出现ModuleNotFoundError: No module named ‘urllib2’

import urllib, urllib2, sys
host = 'http://freecityid.market.alicloudapi.com'
path = '/whapi/json/alicityweather/briefforecast3days'
method = 'POST'
appcode = '你自己的AppCode'
querys = ''
bodys = {}
url = host + path

bodys['cityId'] = '''2'''
bodys['token'] = '''677282c2f1b3d718152c4e25ed434bc4'''
post_data = urllib.urlencode(bodys)
request = urllib2.Request(url, post_data)
request.add_header('Authorization', 'APPCODE ' + appcode)
//根据API的要求,定义相对应的Content-Type
request.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
response = urllib2.urlopen(request)
content = response.read()
if (content):
    print(content)

如何处理呢?因为python3对urllib2进行整合了,修改可运行的代码如下:
注:以下appcode要更改为自己的appcode,
没有的朋友可以在这里进行申请https://market.aliyun.com/products/57096001/cmapi023656.html?spm=5176.2020520132.101.2.6d727218rZN0JX#sku=yuncode1765600000

import urllib.request, urllib.parse
host = 'http://freecityid.market.alicloudapi.com'
path = '/whapi/json/alicityweather/briefforecast3days'
method = 'POST'
appcode = '你的AppCode码'
querys = ''
bodys = {}
url = host + path
bodys['cityId'] = '''2'''
bodys['token'] = '''677282c2f1b3d718152c4e25ed434bc4'''
post_data = urllib.parse.urlencode(bodys).encode(encoding='utf-8')
request = urllib.request.Request(url, post_data)
request.add_header('Authorization', 'APPCODE ' + appcode)
# //根据API的要求,定义相对应的Content-Type
request.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
response = urllib.request.urlopen(request)
content = str(response.read(), 'utf-8')
if (content):
    print(content)

看最终版吧,修改过后的
简简单单的几行代码搞定

import requests
cityId = '2'
rep = 'http://freecityid.market.alicloudapi.com/whapi/json/alicityweather/briefforecast3days'
data = {'cityId': cityId, }
# 这里你的appCode码要填写你自己的码
ret = requests.post(rep, headers={'Authorization': 'APPCODE {}'.format('你的AppCode码')}, data=data)
ret.encoding = 'utf-8'

print(ret.json())

这里是最后的成果啦
Python3调用阿里云接口,重新方法,解决ModuleNotFoundError: No module named 'urllib2'_第1张图片

你可能感兴趣的:(python,django,API)