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】
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
The sidebar is recommended
- Django ORM details - fields, attributes, operations
- Python web crawler - crawling cloud music review (3)
- Stroke list in python (bottom)
- What cat is the most popular? Python crawls the whole network of cat pictures. Which one is your favorite
- [algorithm learning] LCP 06 Take coins (Java / C / C + + / Python / go / trust)
- Python shows the progress of downloading files from requests
- Solve the problem that Django celery beat prompts that the database is incorrectly configured and does not support multiple databases
- Bamboolib: this will be one of the most useful Python libraries you've ever seen
- Python quantitative data warehouse construction 3: data drop library code encapsulation
- The source code and implementation of Django CSRF Middleware
guess what you like
-
Python hashlib module
-
The cover of Python 3 web crawler development (Second Edition) has been determined!
-
The introduction method of executing Python source code or Python source code file (novice, please enter the old bird and turn left)
-
[Python basics] explain Python basic functions in detail, including teaching and learning
-
Python web crawler - crawling cloud music review (4)
-
The first step of scientific research: create Python virtual environment on Linux server
-
Writing nmap scanning tool in Python -- multithreaded version
-
leetcode 2057. Smallest Index With Equal Value(python)
-
Bamboolib: this will be one of the most useful Python libraries you've ever seen
-
Python crawler actual combat, requests module, python realizes capturing a video barrage
Random recommended
- [algorithm learning] 1108 IP address invalidation (Java / C / C + + / Python / go / trust)
- Test platform series (71) Python timed task scheme
- Java AES / ECB / pkcs5padding encryption conversion Python 3
- Loguru: the ultimate Python log solution
- Blurring and anonymizing faces using OpenCV and python
- How fast Python sync and async execute
- Python interface automation test framework (basic) -- common data types list & set ()
- Python crawler actual combat, requests module, python realizes capturing video barrage comments of station B
- Python: several implementation methods of multi process
- Sword finger offer II 054 Sum of all values greater than or equal to nodes | 538 | 1038 (Java / C / C + + / Python / go / trust)
- How IOS developers learn python programming 3-operator 2
- How IOS developers learn python programming 2-operator 1
- [Python applet] 8 lines of code to realize file de duplication
- Python uses the pynvml tool to obtain the working status of GPU
- Data mining: Python actual combat multi factor analysis
- Manually compile opencv on MacOS and Linux and add it to Python / C + + / Java as a dependency
- Use Python VTK to batch read 2D slices and display 3D models
- Complete image cutting using Python version VTK
- Python interface automation test framework (basic) -- common data types Dict
- Django (make an epidemic data report)
- Python specific text extraction in actual combat challenges the first step of efficient office
- Daily python, Part 8 - if statement
- Django model class 1
- The same Python code draws many different cherry trees. Which one do you like?
- Python code reading (Chapter 54): Fibonacci sequence
- Django model class 2
- Python crawler Basics
- Mapping 3D model surface distances using Python VTK
- How to implement encrypted message signature and verification in Python -- HMAC
- leetcode 1945. Sum of Digits of String After Convert(python)
- leetcode 2062. Count Vowel Substrings of a String(python)
- Analysis of Matplotlib module of Python visualization
- Django permission management
- Python integrated programming -- visual hot search list and new epidemic situation map
- [Python data collection] scripy realizes picture download
- Python interface automation test framework (basic part) -- loop statement of process control for & while
- Daily python, Chapter 9, while loop
- Van * Python | save the crawled data with docx and PDF
- Five life saving Python tips
- Django frequency control