天天看點

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