0
点赞
收藏
分享

微信扫一扫

python 数据请求

mjjackey 2022-09-22 阅读 11


引入一个包

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'])

 

举报

相关推荐

0 条评论