Get the weather with Python requests

It was rainy season so I wanted to know the weather so I made it

  1. [About requests](About #requests)
  2. [Weather acquisition location](#Weather acquisition location)
  3. Source
  4. [Source explanation](#Source explanation)
  5. [Execution result](# Execution result)
  6. Summary

About requests

--Python library for HTTP communication. --Used for retrieving data from HTML and XML files by web scraping. --You can install it by typing ``` pip install requests` `` at the command prompt.

import requests

r = requests.get("https://news.yahoo.co.jp/")
print(r.text)

--Execution result (partial excerpt)

<!DOCTYPE html>
     <style data-styled="gpQmdr jhlPYu" data-styled-version="4.4.1" data-styled-streamed="true">
     /* sc-component-id: sc-jAaTju */
     .gpQmdr{display:-webkit-box;display:-webkit-flex;display:-ms- flexbox;display:flex;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;overflow:hidden;position:relative;background-color:#efefef;height:80px;width:80px;} .gpQmdr::after{content:'';display:block;position:absolute;top:0;left:0;box-sizing:border-box;width:100%;height:100%;border:solid 1px rgba(0,0,0,0.06);}

Where to get the weather

[Weather Web Service] for livedoor weather information (http://weather.livedoor.com/weather_hacks/webservice) Search for the id of the "primary subdivision (city tag)" of the requested area in the link of the point definition table nationwide on the above site. (Example: Kyoto Prefecture, Kyoto City = 260010)

Source

import requests

class GetWeather:
    url = "http://weather.livedoor.com/forecast/webservice/json/v1?"

    def getWeather(self, citycode):
        query_params = {"city": citycode}
        self.data = requests.get(self.url, params = query_params).json()

    def showWeather(self):
        print(self.data["location"]["city"], "The weather is")
        for weather in self.data["forecasts"]:
            print(weather["date"])
            print(weather["dateLabel"] + "Weather:" + weather["telop"])
            print("")

citycode = 260010
w = GetWeather()
w.getWeather(citycode)
w.showWeather()

Source commentary

The first line

import requests

Import requests library

3rd line

class GetWeather

Definition of the GetWeather class.

4th line

url = "http://weather.livedoor.com/forecast/webservice/json/v1?"

URL when requesting JSON data

Lines 6-8 getWeather method

def getWeather(self, citycode):
    query_params = {"city": citycode}
    self.data = requests.get(self.url, params = query_params).json()

Line 6: Definition of the getWeather method. Specify the area code as an argument. A method to get the weather data.

Line 7: Assign region code to query_params.

8th line: Get weather data with requests.get (). With this, you can get the weather of the area of the code specified by query_params with the area code set in the url.

Lines 10-15 showWeather method

def showWeather(self):
    print(self.data["location"]["city"], "The weather is")
    for weather in self.data['forecasts']:
        print(weather["date"])
        print(weather["dateLabel"] + "Weather:" + weather["telop"])
        print("")

Line 10: Definition of showWeather method. A method to display the acquired weather.

Line 11: If you look at the property name of the response field of the weather web service specification, you can see that the city property of the location property has the primary subdivision name, so `self.data ["location "] [" city You can display the primary subdivision name of the city property with "]`.

Line 12: Similarly, you can see that the date property of the forecasts property has the forecast date (year / month / day) and the dataLabel property has the forecast date (today, tomorrow, or the day after tomorrow).

Extract the properties in the forecasts property with.



 Line 13: `` `print (weather [" date "])` `` to display the date property

 Line 14: `` `print (weather [" dateLabel "] +" weather: "+ weather [" telop "])` ``
 Display dateLabel property and telop property

### Lines 17-20
 Line 17: Definition of city code. (Here, Kyoto City, Kyoto Prefecture)
 Line 18: Creating an instance of the GetWeather class.
 Line 19: Call to getWeather method.
 Line 20: Call to showWeather method.

## Execution result

The weather in Kyoto is 2020-06-19 Today's weather: cloudy after rain

2020-06-20 Tomorrow's weather: cloudy then sunny

2020-06-21 The day after tomorrow: sunny and sometimes cloudy


## Summary
 --HTTP communication is possible with requests
 ――It might be interesting if you can get the weather of the prefecture and area specified by the user.
 --It's better to see the weather normally y ('^' c 彡 ☆)) Д´) Pan
 -[Continued (Getting the weather with Python requests 2)](https://qiita.com/gs_project_py25/items/5edf946348b63b2a78b9)


Recommended Posts

Get the weather with Python requests
Get the weather with Python requests 2
Get weather information with Python & scraping
[Python] Get the variable name with str
Get date with python
Retry with python requests
[Python] Get the files in a folder with Python
Get the weather in Osaka via WebAPI (python)
Get country code with python
Get Twitter timeline with python
Get Youtube data with python
[Python] Get the previous month
Get thread ID with python
Scraping weather forecast with python
Get started with Python! ~ ② Grammar ~
Call the API with python3.
Get stock price with Python
Get home directory with python
Get keyboard events with python
Get Alembic information with Python
[Python] Get the numbers in the graph image with OCR
Get the result in dict format with Python psycopg2
Get the operation status of JR West with Python
Extract the xz file with python
Get started with Python! ~ ① Environment construction ~
Link to get started with python
Get reviews with python googlemap api
Minimum knowledge to get started with the Python logging module
[Python] POST wav files with requests [POST]
Get web screen capture with python
[Python] Get economic data with DataReader
Get the script path in Python
How to get the Python version
Find the Levenshtein Distance with python
Let's touch the API of Netatmo Weather Station with Python. #Python #Netatmo
How to get started with Python
Hit the Etherpad-lite API with Python
Install the Python plugin with Netbeans 8.0.2
[Small story] Get timestamp with Python
I liked the tweet with python. ..
Get Qiita trends with Python scraping
Get upcoming weather from python weather api
[Python] Get the script execution directory with an absolute path
How to get into the python development environment with Vagrant
Get the desktop path in Python
Master the type with Python [Python 3.9 compatible]
System trade starting with Python3: Get the latest program code
Get the host name in Python
Python Note: Get the current month
Send multipart / form-data with python requests
Get started with Python in Blender
[Introduction to Python] How to get data with the listdir function
Get the source of the page to load infinitely with python.
How is the progress? Let's get on with the boom ?? in Python
I want to know the weather with LINE bot feat.Heroku + Python
Get started with the Python framework Django on Mac OS X
The fastest way to get camera images regularly with python opencv
PhytoMine-I tried to get the genetic information of plants with Python
Make the Python console covered with UNKO
Tweet the weather forecast with a bot
Get additional data in LDAP with python