PythonPython obtains weather data

Python gets weather data

Checking the weather seems fairly simple: open a web browser, click on the address bar, enter the URL of a weather website (or search for one and click on the link), wait for the page to load, skip all the ads, etc.

In fact, if there is a program that downloads the weather forecast for the next few days and prints it out in plain text, you can skip a lot of boring steps. This program uses the requests module introduced in Chapter 11 to download data from the website. Overall, this program will do the following:

Read the requested location from the command line.

Download JSON weather data from OpenWeatherMap.org.

Convert JSON data strings into Python data structures.

Print the weather for today and the next two days.

Therefore, the code needs to accomplish the following tasks:

Concatenate the strings in sys.argv to get the position.

Call requests.get() to download weather data.

Call json.loads() to convert JSON data into Python data structure.

Print weather forecast.

For this project, open a new file editor window and save it as quickWeather.py.

Step 1: Get location from command line parameters

The input to this program comes from the command line. Let quickWeather.py look like this:

#!python3

quickWeather.py – Prints the weather for a location from the command line.

import json, requests, sys

Compute location from command line arguments.

if len(sys.argv) < 2:
print(Usage: quickWeather.py location’)
sys.exit()
location=“Changchun”
#T0D0: Download the JSON data from OpenWeatherMap.org’s API.

#T0D0: Load JSON data into a Python variable.
In Python, command line arguments are stored in the sys.argv list. After the #! line and the import statement, the program checks to see if there are multiple command line arguments (recall that there is at least one element in sys.argv, sys.argv[0], which contains the filename of the Python script). If there is only one element in the list, and the user did not provide a position on the command line, the program provides the user with “Usage” information and then ends.

Command line arguments are separated by spaces. The command line parameter San Francisco, CA will save [quickWeather.py’, San’, Francisco’, CA’] in sys.argv. Therefore, the join() method is called to join the strings in sys.argv except the first string. Store the concatenated string in the variable location.

Step 2: Download JSON data

OpenWeatherMap.org provides real-time weather information in JSON format. Your program only needs to download the page http://api.openweathermap.org/data/2.5/forecast/daily?q= & amp;cnt=3, which is the city where you want to know the weather. Add the following code to quickWeather.py.

#!python3

quickWeather.py – Prints the weather for a location from the command line.

import json, requests, sys

Compute location from command line arguments.

if len(sys.argv) < 2:
print(Usage: quickWeather.py location’)
sys.exit()
location=“Changchun”
weatherJsonUrl = “http://wthrcdn.etouch.cn/weather_mini?city=%s” % (location)
response = requests.get(weatherJsonUrl)

try:

response.raise_for_status()

except:

print("URL request error")

response = requests.get(weatherJsonUrl)

weatherData = json.loads(response.text)

w = weatherData[data’]

TODO: Load JSON data into a Python variable.

We get the location from the command line argument. In order to generate the URL to be accessed, we use the %s placeholder to insert the string saved in location into the URL string at that position. The result is saved in the url and the url is passed into requests.get() . The requests.get() call returns a Response object, which can be checked for errors by calling raise_for_status(). If no exception occurs, the downloaded text will be saved in response.text.

Step 3: Load JSON data and print weather

The response.text member variable stores a large string of JSON format data. To convert it to a Python value, call the json.loads() function. The JSON data will look like this:

{city’:{coord’: {lat’: 37.7771, Ion’: -122.42}, country’: ’ United States of America’, id’: 5391959’,
name’: San Francisco’, population’: 0},
cnt’:3,
cod’:200,
‘list’:[{‘clouds’: 0,’deg’: 233,’dt’: 1402344000,’humidity’: 58,’pressure’: 1012.23, ‘speed1: 1.96,
temp’: {day’: 302.29, eve’: 296.46, max’: 302.29, min’:289.77, morn’: 294.59, night’: 289.77},
‘weather’: [{‘description’:’sky is clear’,
icon’:01d’,
–snip–
You can pass weatherData into pprint.pprint to view this data. You may want to look at http://openweathermap.org/ to find documentation on the meaning of these fields. For example, the online documentation will tell you that the 302.29 after ‘day’ is the daytime temperature in Kelvin, not Celsius or Fahrenheit.

The weather description you want comes after ‘nain’ and ‘description’. To print it out neatly, add the following code in quickWeather.py.

#!python3

quickWeather.py – Prints the weather for a location from the command line.

import json, requests, sys

Compute location from command line arguments.

if len(sys.argv) < 2:
print(Usage: quickWeather.py location’)
sys.exit()
location=“Changchun”
weatherJsonUrl = “http://wthrcdn.etouch.cn/weather_mini?city=%s” % (location)
response = requests.get(weatherJsonUrl)

try:

response.raise_for_status()

except:

print("URL request error")

response = requests.get(weatherJsonUrl)

weatherData = json.loads(response.text)

w = weatherData[data’]

print(“Location: %s” % w[city’])

date_a = []

highTemp = []

lowTemp = []

weather = []

for i in range(len(w[forecast’])):
date_a.append(w[forecast’][i][date’])

highTemp.append(w['forecast'][i]['high'])

lowTemp.append(w['forecast'][i]['low'])

weather.append(w['forecast'][i]['type'])

print('Weather location %s:' % (location))
print("Date:" + date_a[i])

print("\tTemperature: most" + lowTemp[i] + '℃~most' + highTemp[i] + '℃')

print("\tWeather: " + weather[i])


print("\
Today's outfit: " + w['ganmao'])

print("Current temperature:" + w['wendu'] + "℃")

Location: Changchun
Weather Location Changchun:
Date: Sunday the 5th
Temperature: lowest temperature 19℃~highest temperature 24℃
Weather: Moderate rain

What to wear today: It is a low-incidence period for colds and the weather is comfortable. Please eat more fruits and vegetables and drink more water.
Current temperature: 19℃
Weather Location Changchun:
Date: Monday 6th
Temperature: lowest temperature 18℃~highest temperature 26℃
Weather: thundershowers

What to wear today: It is a low-incidence period for colds and the weather is comfortable. Please eat more fruits and vegetables and drink more water.
Current temperature: 19℃
Weather Location Changchun:
Date: Tuesday the 7th
Temperature: lowest temperature 17℃~highest temperature 27℃
Weather: cloudy

What to wear today: It is a low-incidence period for colds and the weather is comfortable. Please eat more fruits and vegetables and drink more water.
Current temperature: 19℃
Weather Location Changchun:
Date: Wednesday 8th
Temperature: lowest temperature 18℃~highest temperature 29℃
sunny

What to wear today: It is a low-incidence period for colds and the weather is comfortable. Please eat more fruits and vegetables and drink more water.
Current temperature: 19℃
Weather Location Changchun:
Date: Thursday 9th
Temperature: lowest temperature 20℃~highest temperature 31℃
sunny

What to wear today: It is a low-incidence period for colds and the weather is comfortable. Please eat more fruits and vegetables and drink more water.
Current temperature: 19℃
Note that the code saves weatherData[‘list’] in the variable w, which will save some typing time. You can use w[0], w[1] and w[2] to get the dictionary of today’s, tomorrow’s and the day after tomorrow’s weather. These dictionaries all have a ‘weather’ key, which contains a list value. What you’re interested in is the first list item (a nested dictionary with several keys), indexed at 0. Here, we print out the values stored in the ‘main’ and ‘description’ keys, separated by a hyphen.

If you run this program with the command line arguments quickWeather.py San Francisco, CA, the output will look like this:

Current weather in San Francisco, CA:
Clear – sky is clear

Tomorrow:
Clouds – few clouds

Day after tomorrow:
Clear – sky is clear