I scraped tenki.jp and incorporated the weather forecast into linebot. https://tenki.jp/
windows python 3.6.4
#Target site URL
url = "https://tenki.jp/forecast/6/30/6200/27100/"
#Instance creation
res = urllib.request.urlopen(url)
soup = BeautifulSoup(res, 'html.parser')
'html.parser' is like a filter needed for scraping.
weather = soup.find_all("p", class_="weather-telop")
temp = soup.find_all("dd", class_="high-temp temp")
low_temp = soup.find_all("dd", class_="low-temp temp")
tds = soup.select("tr.rain-probability td")
hini = soup.find_all("h3", class_="left-style")
From the top, scraping is done in the order of "weather, temperature, minimum temperature, probability of precipitation, date". I need to get used to using find_all and select methods properly, but I thought that there would be no problem if I used only select.
tenki = hini[0].getText() + "\n\n" + weather[0].getText()
kion = "\n best" + temp[0].getText()
low_kion = "Minimum" + low_temp[0].getText()
rain1 = "\n\n Precipitation probability\n00-06:00" + tds[0].getText()
rain2 = "\n06-12 o'clock" + tds[1].getText()
rain3 = "\n12-18:00" + tds[2].getText()
rain4 = "\n18-24:00" + tds[3].getText()
All the scraped items will be obtained as a list. This time, basically, the content of [0] was today's data, and the content of [1] was tomorrow's data, so it was relatively easy.
import urllib.request
from bs4 import BeautifulSoup
def getw():
#Target site URL
url = "https://tenki.jp/forecast/6/30/6200/27100/"
#Instance creation
res = urllib.request.urlopen(url)
soup = BeautifulSoup(res, 'html.parser')
#Target element
#today's weather
weather = soup.find_all("p", class_="weather-telop")
temp = soup.find_all("dd", class_="high-temp temp")
low_temp = soup.find_all("dd", class_="low-temp temp")
tds = soup.select("tr.rain-probability td")
hini = soup.find_all("h3", class_="left-style")
tenki = hini[0].getText() + "\n\n" + weather[0].getText()
kion = "\n best" + temp[0].getText()
low_kion = "Minimum" + low_temp[0].getText()
rain1 = "\n\n Precipitation probability\n00-06:00" + tds[0].getText()
rain2 = "\n06-12 o'clock" + tds[1].getText()
rain3 = "\n12-18:00" + tds[2].getText()
rain4 = "\n18-24:00" + tds[3].getText()
a = tenki+kion+low_kion+rain1+rain2+rain3+rain4
return a
After that, load this function into main.py of linebot.
text_in = event.message.text
if "today" in text_in:
line_bot_api.reply_message(event.reply_token,TextSendMessage(text=scw.getw()))
When a user enters a character that contains the word "today", today's weather is displayed. Then deploy and complete!
I should be able to write smarter, so I will leave it as an issue next. Also, since it is a BOT that is not interesting at all, there are many things that can be done, such as adding arrangements such as "Have you got an umbrella?" If it rains, so let's leave this as the next task.
It doesn't matter at all, but my back hurts.
Recommended Posts