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

2 篇文章 0 订阅
1 篇文章 0 订阅

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())

这里是最后的成果啦
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值