current position:Home>Python crawls the map of Gaode and the weather conditions of each city

Python crawls the map of Gaode and the weather conditions of each city

2022-01-31 11:09:00 bosaidongmomo

image.png


import time

import requests
from prettytable import PrettyTable     # Library for printing tables 
'''  Check the weather of the current location url:https://www.amap.com/service/weather?adcode=110000  Corresponding to each city code Of url:https://www.amap.com/service/cityList?version=20207  remarks : these two items. url It can be downloaded from Network See  '''

#  Get the name corresponding to the place name code
def get_location_dic(location_dic_url,province):

    #  Judge whether the entered province name is correct 
    list = [' The Beijing municipal ', ' tianjin ', ' Hebei Province ', ' Shanxi Province ', ' Inner Mongolia Autonomous Region ', ' Liaoning Province ', ' Jilin Province ', ' Heilongjiang Province ', ' Shanghai ', ' Jiangsu Province ', ' Zhejiang Province ', ' Anhui Province ', ' Fujian Province ', ' Jiangxi Province ', ' Shandong Province ', ' Henan province ',
     ' Hubei province ', ' Hunan province ', ' Guangdong province, ', ' Guangxi Zhuang Autonomous Region ', ' Hainan ', ' Chongqing City ', ' Sichuan Province ', ' Guizhou Province ', ' Yunnan Province ', ' Tibet Autonomous Region ', ' Shaanxi Province ', ' Gansu Province ', ' Qinghai Province ', ' Ningxia Hui Autonomous Region ',
     ' Xinjiang Uygur Autonomous Region ', ' Taiwan Province ', ' Hong Kong Special Administrative Region ', ' Macao SAR ']

    if province not in list:
        print('_'*100)
        print(':(  Input error ! Please enter the correct province name ')
        print(' Tips : The province name that can be entered is :')
        print(list)
    else:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36'}

        response = requests.get(location_dic_url,headers=headers)
        response.encoding = response.apparent_encoding

        #  obtain json data 
        data = response.json()['data']['cityData']['provinces']

        #  Create a dictionary to save the data of each province code
        provinces_code_dic = {}
        for d in data:
            provinces_code_dic[data[d]['label']] = data[d]['adcode']

        #  Gets the of all cities in the specified province code Etc 
        cities_data = data[provinces_code_dic[province]]['cities']

        #  There are no cities in municipalities directly under the central government , At this point, you can directly return to the previous level, including municipalities directly under the central government code Content of information .
        if not cities_data:
            cities_data = [data[provinces_code_dic[province]]]
        return cities_data
    return ''


#  Back from Gaud map json Get key parts from data 
def get_today_data(url,location_code):
    weather_url = url + location_code
    response = requests.get(weather_url)
    response.encoding = response.apparent_encoding
    today_data = response.json()['data']['data'][0]
    return today_data

#  Extract the weather information of the current location from the data obtained above and assign it to the object wheather
#  from json As can be seen from the data , The weather data of Gaode map is divided into day and night 
def get_wheather(today_data):
    wheather = {
        'day_wheather': {
            'max_temp': today_data['forecast_data'][0]['max_temp'],
            'min_temp': today_data['forecast_data'][0]['min_temp'],
            'weather_name': today_data['forecast_data'][0]['weather_name'],
            'wind_power_desc': today_data['forecast_data'][0]['wind_power_desc'],
            'wind_direction_desc': today_data['forecast_data'][0]['wind_direction_desc']
        },
        'night_wheather': {
            'max_temp': today_data['forecast_data'][1]['max_temp'],
            'min_temp': today_data['forecast_data'][1]['min_temp'],
            'weather_name': today_data['forecast_data'][1]['weather_name'],
            'wind_power_desc': today_data['forecast_data'][1]['wind_power_desc'],
            'wind_direction_desc': today_data['forecast_data'][1]['wind_direction_desc']
        }
    }
    return wheather



if __name__ == '__main__':
    while True:
        province = input(' Please enter the province name :')
        print(' Crawling up , Please later ...')
        print('')
        url = 'https://www.amap.com/service/weather?adcode='
        location_dic_url = 'https://www.amap.com/service/cityList?version=20207'

        #  Define an empty list to store the weather information of all cities 
        all_info = []

        #  Get the corresponding information of each city code And other information 
        location_dic_all = get_location_dic(location_dic_url,province)

        if location_dic_all:
            #  Remove useless information , Only keep   City :code
            location_dic = [
                {
                    base['name']:base['adcode'] for base in location_dic_all
                }
            ]

            #  Extract the list of city names 
            locations = location_dic[0].keys()

            #  Traverse city names , Extract all the required information and assign it to all_info
            for location in locations:
                today_data = get_today_data(url,location_dic[0][location])
                wheather = get_wheather(today_data)
                all_info.append(
                    {
                        'location':location,
                        'day_wheather':wheather['day_wheather'],
                        'night_wheather':wheather['night_wheather']
                    }
                )
            today = today_data['forecast_date']
            weekday = str(today_data['weekday'])

            #  The data contains 1-7 On behalf of the week , Match it to Monday in the dictionary 
            weekday_dic = {
                '1':' Tuesday ',
                '2':' Wednesday ',
                '3':' Thursday ',
                '4':' Friday ',
                '5':' Saturday ',
                '6':' Sunday ',
                '7':' Monday ',
            }

            #  Call this module to print the form 
            tb = PrettyTable()
            tb.field_names = [' City ',' Sooner or later ',' The weather ',' maximum temperature ',' Minimum temperature ',' wind ']
            for x in all_info:
                tb.add_row([x['location'],' Day ',x['day_wheather']['weather_name'],x['day_wheather']['max_temp'],x['day_wheather']['min_temp'],x['day_wheather']['wind_direction_desc'] + ' ' + x['day_wheather']['wind_power_desc']])
                tb.add_row(['',' night ',x['night_wheather']['weather_name'],x['night_wheather']['max_temp'],x['night_wheather']['min_temp'],x['night_wheather']['wind_direction_desc'] + ' ' + x['night_wheather']['wind_power_desc']])
            print(' It's today %s %s.%s The weather is as follows :'%(today,weekday_dic[weekday],province))
            print(tb)
        print('*'*100)
 Copy code 

copyright notice
author[bosaidongmomo],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201311108581042.html

Random recommended