python 数据请求

引入一个包

from urllib.request import urlopen
import string
import json

from prettyprinter import pprint
url不能写中文    之所以我们能够在url中看到中文
是因为浏览器处于用户友好的目的
为了让用户识别特意显示的
但是在url执行的时候  中文会被转码
如果不进行转码   程序会出错
url = 'http://api.map.baidu.com/telematics/v3/weather?location=郑州市&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'
responese = urlopen(quote(url,safe = string.printable))
urlopen不支持中英文混写
responeseData = responese.read()
print(responeseData)
地址栏不支持使用中文,所以需要进行转码
 转码的时候   不但会将中文进行转码
 同时也会将一些特殊符号进行转码   比如:?
 如果不想让这些特殊符号进行转码
 就要使用安全转码(只会转码中文)
print('没有使用safe\n{}'.format(quote(url)))
print('使用了safe\n{}'.format(quote(url,safe=string.printable)))
print(responeseJson['date'])
for dict in responeseJson['results'][0]['index']:
    print(dict['des'])
    print(dict['tipt'])
for dict in responeseJson['results'][0]['weather_data']:
    print(dict['date'])
    print(dict['temperature'])

下面是完整代码:

from urllib.request import urlopen
from urllib.parse import quote
import string
import json
from prettyprinter import pprint



url = 'http://api.map.baidu.com/telematics/v3/weather?location=郑州市&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'
responese = urlopen(quote(url,safe = string.printable))

responeseData = responese.read()
print(responeseData)

print('没有使用safe\n{}'.format(quote(url)))
print('使用了safe\n{}'.format(quote(url,safe=string.printable)))

responeseJson = json.loads(responeseData)
pprint(responeseJson)

print(responeseJson['date'])
for dict in responeseJson['results'][0]['index']:
    print(dict['des'])
    print(dict['tipt'])
for dict in responeseJson['results'][0]['weather_data']:
    print(dict['date'])
    print(dict['temperature'])

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值