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.
--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
<title> hoge hoge </ title>` ``, `` `<link rel =" stylesheet "href =" # ">` `` `` `rel`` `,` `Href
, etc. are called attributes.Format the previous source for this source.
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()
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
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)
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)
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
.
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 variable
i. 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```.
Line 1: Definition of showArea method. The selected state / region display method. 2nd line: Outputs the specified prefecture. 3rd line: Output the selected area.
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()
--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