資源簡介
Python 天氣 爬蟲 一個(gè)簡單Python 代碼 爬取天氣信息 搬運(yùn)工

代碼片段和文件信息
import?urllib.request
import?gzip
import?json
print(‘------天氣查詢------‘)
def?get_weather_data()?:
????city_name?=?input(‘請輸入要查詢的城市名稱:‘)
????url1?=?‘http://wthrcdn.etouch.cn/weather_mini?city=‘+urllib.parse.quote(city_name)
????url2?=?‘http://wthrcdn.etouch.cn/weather_mini?citykey=101010100‘
????#網(wǎng)址1只需要輸入城市名,網(wǎng)址2需要輸入城市代碼
????#print(url1)
????weather_data?=?urllib.request.urlopen(url1).read()
????#讀取網(wǎng)頁數(shù)據(jù)
????weather_data?=?gzip.decompress(weather_data).decode(‘utf-8‘)
????#解壓網(wǎng)頁數(shù)據(jù)
????weather_dict?=?json.loads(weather_data)
????#將json數(shù)據(jù)轉(zhuǎn)換為dict數(shù)據(jù)
????return?weather_dict
def?show_weather(weather_data):
????weather_dict?=?weather_data?
????#將json數(shù)據(jù)轉(zhuǎn)換為dict數(shù)據(jù)
????if?weather_dict.get(‘desc‘)?==?‘invilad-citykey‘:
????????print(‘你輸入的城市名有誤,或者天氣中心未收錄你所在城市‘)
????elif?weather_dict.get(‘desc‘)?==‘OK‘:
????????forecast?=?weather_dict.get(‘data‘).get(‘forecast‘)
????????print(‘城市:‘weather_dict.get(‘data‘).get(‘city‘))
????????print(‘溫度:‘weather_dict.get(‘data‘).get(‘wendu‘)+‘℃?‘)
????????print(‘感冒:‘weather_dict.get(‘data‘).get(‘ganmao‘))
????????print(‘風(fēng)向:‘forecast[0].get(‘fengxiang‘))
????????print(‘風(fēng)級(jí):‘forecast[0].get(‘fengli‘))
????????print(‘高溫:‘forecast[0].get(‘high‘))
????????print(‘低溫:‘forecast[0].get(‘low‘))
????????print(‘天氣:‘forecast[0].get(‘type‘))
????????print(‘日期:‘forecast[0].get(‘date‘))
????????print(‘*******************************‘)
????????four_day_forecast?=input(‘是否要顯示未來四天天氣,是/否:‘)
????????if?four_day_forecast?==?‘是‘?or?‘Y‘?or?‘y‘:
????????????for?i?in?range(15):
????????????????print(‘日期:‘forecast[i].get(‘date‘))
????????????????print(‘風(fēng)向:‘forecast[i].get(‘fengxiang‘))
????????????????print(‘風(fēng)級(jí):‘forecast[i].get(‘fengli‘))
????????????????print(‘高溫:‘forecast[i].get(‘high‘))
????????????????print(‘低溫:‘forecast[i].get(‘low‘))
????????????????print(‘天氣:‘forecast[i].get(‘type‘))
????????????????print(‘--------------------------‘)
????print(‘***********************************‘)
show_weather(get_weather_data())
?屬性????????????大小?????日期????時(shí)間???名稱
-----------?---------??----------?-----??----
?????文件????????2262??2015-06-07?14:51??weather2.py
評(píng)論
共有 條評(píng)論