Get the weather with Python requests 2

I want to implement the weather acquisition of the user-specified prefecture and region described in the summary of the previous ** Get weather with Python requests ** I made it because I thought.

  1. [About BeatifulSoup](About #BeatifulSoup)
  2. [Last source](#Last source)
  3. [Processing part source](# Processing part source)
  4. [Source explanation of processing part](# Source explanation of processing part)
  5. [Source of execution part](# Source of execution part)
  6. Summary

About Beautiful Soup

--Python web scraping library that retrieves and parses data from HTML and XML files. --You can install by typing `` `pip install beautifulsoup4``` at the command prompt.

import requests
from bs4 import BeautifulSoup

#Get the linked HTML source
html = requests.get("http://www.google.com")
soup = BeautifulSoup(html.text, "html.parser")

#Get the first title tag and output each tag
print(soup.find("title"))

#Get the first title tag and output only the element
print(soup.title.string)
<title>Google</title>
Google

Last source

Format the previous source for this source.

Before plastic surgery

import requests
#from bs4 import Add Beautiful Soup

class GetWeather:
    url = "http://weather.livedoor.com/forecast/webservice/json/v1?"
    #Added URL of national location definition table (RSS) for weather service(Web scraping destination)
    # http://weather.livedoor.com/forecast/rss/primary_area.xml

    def getWeather(self, citycode): #Remove the argument citycode
        query_params = {"city": citycode} #Variable citycode as a class variable
        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 #Delete
#Deleted below
w = GetWeather()
w.getWeather(citycode)
w.showWeather()

After plastic surgery

import requests
from bs4 import BeautifulSoup #add to

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

    #Add source here
    

    def getWeather(self): #Remove the argument citycode
        query_params = {"city": self.citycode} #Variable citycode as an instance variable
        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("")

#Add execution part here

Source of processing part

The source of the addition is shown below (please be careful about indentation etc. when adding)

#Add instance variable
self.pref = ""     #Storage of designated prefectures
self.citys = ""    #Storage of areas in designated prefectures
self.city = ""     #Storage of designated area
self.citycode = "" #Storage of area code of specified area

#constructor
def __init__(self):
    self.html = requests.get(self.source)
    self.soup = BeautifulSoup(self.html.text, "html.parser")
    self.prefs = self.soup.find_all("pref")

#Prefecture search method
def findPref(self, pref):
    for i in self.prefs:
        title = i.get("title")

        if title == pref:
            self.pref = title
            self.citys = i.find_all("city")

#Region search method
def selectCity(self):
    count = 1   #counter
    titles = {} #dictionary

    for i in self.citys:
        titles[i.get("title")] = i.get("id")

    for i in titles:
        print("area", count, ":", i)
        count += 1 #count up

    self.city = input("Please enter the area where you want to know the weather. >>>")

    for i in titles:
        if i == self.city:
            self.citycode = titles[i]

#Selected prefecture / region display method
def showArea(self):
    print("Prefectures:", self.pref)
    print("area:", self.city)

Source explanation of the processing part

Constructor (init method)

Line 1: Constructor definition. Automatically executed when an instance is created. 2nd line: Get HTML source Line 3: HTML parsing 4th line: Get pref tag (list)

findPref method

Line 1: Definition of the findPref method. Prefecture search method. 2nd line: Extract tags one by one from the list containing pref tags and assign them to the variable i. 3rd line: Extract and assign the `title``` attribute from the pref``` tag stored in the ```i``` to the variable `` title```.

Line 5: Check if the title and the argument pref are equal. Line 6: If equal, assign to the instance variable `` `pref. Line 7: Assign the city tag contained in the pref tag to the instance variable` `citys.

selectCity method

Line 1: Definition of selectCity method. Region search method. Line 5: Take tags one by one from the list containing the city tags and assign them to the variable `i```. 6th line: Extract the title``` attribute of the city``` tag and specify it as the key. Extract the ```id``` attribute of the city``` tag and assign it to the element. Line 8: Take the keys one by one from the dictionary ``` titles``` and assign them to the variable ```i```. 9th line: ``` Region n (count): Output as region name . 12th line: Enter the area name you want to specify. Line 14: Take out the keys one by one from the dictionary `` titlesand assign them to the variablei. Line 15: Check if i and the instance variable `` `city are equal. Line 16: If equal, assign the element of `titles [i] ``` to the instance variable `citycode```.

showArea method

Line 1: Definition of showArea method. The selected state / region display method. 2nd line: Outputs the specified prefecture. 3rd line: Output the selected area.

Source of execution part

Add the source of the execution part.

w = GetWeather() #Instance generation

#Enter prefecture
pref = input("Please enter the prefecture where you want to know the weather. >>>")
w.findPref(pref)
w.selectCity()
w.showArea()
w.getWeather()
w.showWeather()

Summary

--BeautifulSoup can retrieve and analyze data from HTML and XML files. ――It might be interesting if you could bookmark the area. ――After all, it's better to see the weather normally y ('^' c 彡 ☆)) Д´) Pan --The previous weather BOT is ** here **

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 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
Get the desktop path in Python
[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