The Wayback Machine - https://web.archive.org/web/20240921213434/https://www.geeksforgeeks.org/scraping-weather-data-using-python-to-get-umbrella-reminder-on-email/
Open In App

Scraping weather data using Python to get umbrella reminder on email

Last Updated : 05 Oct, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we are going to see how to scrape weather data using Python and get reminders on email. If the weather condition is rainy or cloudy this program will send you an “umbrella reminder” to your email reminding you to pack an umbrella before leaving the house.  We will scrape the weather information from Google using bs4 and requests libraries in python. 

Then based on the weather conditions we will send the email using smtplib library. To run this program every day at a specified time we will use the schedule library in python.

Modules Needed

  • bs4: Beautiful Soup (bs4) is a Python library for extracting data from HTML and XML files. To install this library, type the following command in IDE/terminal.
pip install bs4
  • requests: This library allows you to send HTTP/1.1 requests very easily. To install this library, type the following command in IDE/terminal.
pip install requests
  • smtplib: smtplib is a Python module that defines an SMTP client session object, which can be used to send mail to any machine on the Internet. To install this library, type the following command in the IDE/terminal.
pip install smtplib
  • schedule: A schedule is a Python library used to schedule tasks at specific times of the day or specific days of the week. To install this library, type the following command in the IDE/terminal.
pip install schedule

Stepwise Implementation

Step 1: Import schedule, smtplib, requests, and bs4 libraries.

Python3




import schedule
import smtplib   
import requests
from bs4 import BeautifulSoup


Step 2: Create a URL with the specified city name and create a requests instance bypassing this URL.

Python3




city = "Hyderabad"
url = "https://www.google.com/search?q=" + "weather" + city
html = requests.get(url).content


Step 3: Pass the retrieved HTML document into Beautiful Soup which will return a string stripped of  HTML tags and metadata.  Using the find function we will retrieve all the necessary data.

Python3




soup = BeautifulSoup(html,
                     'html.parser')
temperature = soup.find(
  'div', attrs={'class': 'BNeawe iBp4i AP7Wnd'}).text
time_sky = soup.find(
  'div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text
  
# formatting data
sky = time_sky.split('\n')[1]


Step 4: If the weather condition turns out to be rainy or cloudy, this program will send an email with an “umbrella reminder” message to the recipient. To encapsulate an SMTP connection I have created an SMTP object with the parameters `smtp.gmail.com` and 587. After creating the SMTP object, you can log in with your email address and password.

Note: Different websites use different port numbers. In this article, we are using a Gmail account to send emails. The port number used here is “587”. If you want to send mail using a website other than Gmail, you need to obtain the corresponding information.

Python3




if sky == "Rainy" or sky == "Rain And Snow" or sky == "Showers" or sky == "Haze" or sky == "Cloudy":
    smtp_object = smtplib.SMTP('smtp.gmail.com', 587)


Step 5: For security reasons, the SMTP connection is now placed in TLS mode. Transport Layer Security encrypts all SMTP commands. After that, for authentication purposes, you need to pass your Gmail account credentials in the login instance. If you enter an invalid email ID or password, the compiler will display an authentication error.  

Save the message you need to send to a variable, like msg. Use the sendmail() instance to send your message. sendmail() uses three parameters: sender_email_id, receiver_email_id, and message_to_be_sent. The order of these three parameters must be the same. This will send an email from your account. After completing the task, use quit () to end the SMTP session.

Python3




# start TLS for security
smtp_object.starttls()
# Authentication
smtp_object.login("YOUR EMAIL", "PASSWORD")
subject = "Umbrella Reminder"
body = f"Take an umbrella before leaving the house.\
Weather condition for today is ", {
    sky}, " and temperature is {temperature} in {city}."
msg = f"Subject:{subject}\n\n{body}\n\nRegards,\
\nGeeksforGeeks".encode('utf-8')
  
# sending the mail
smtp_object.sendmail("FROM EMAIL ADDRESS",
                     "TO EMAIL ADDRESS", msg)
# terminating the session
smtp_object.quit()
print("Email Sent!")


Step 6:  Using the schedule library, Schedule the task every day at a specific time. schedule.run_pending() Checks whether a scheduled task is pending to run or not.

Python3




# Every day at 06:00AM time umbrellaReminder() is called.
schedule.every().day.at("06:00").do(umbrellaReminder)
  
while True:
    schedule.run_pending()


Note: When you execute this program it will throw you a smtplib.SMTPAuthenticationError and also sends you a Critical Security alert to your email because, In a nutshell, Google is not allowing you to log in via smtplib because it has flagged this sort of login as “less secure”, so what you have to do is go to this link while you’re logged in to your google account, and allow the access:

Below is the full implementation:

Python3




import schedule
import smtplib
import requests
from bs4 import BeautifulSoup
  
  
def umbrellaReminder():
    city = "Hyderabad"
      
    # creating url and requests instance
    url = "https://www.google.com/search?q=" + "weather" + city
    html = requests.get(url).content
      
    # getting raw data
    soup = BeautifulSoup(html, 'html.parser')
    temperature = soup.find('div',
                            attrs={'class': 'BNeawe iBp4i AP7Wnd'}).text
    time_sky = soup.find('div', 
                         attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text
      
    # formatting data
    sky = time_sky.split('\n')[1]
  
    if sky == "Rainy" or sky == "Rain And Snow" or sky == "Showers" or sky == "Haze" or sky == "Cloudy":
        smtp_object = smtplib.SMTP('smtp.gmail.com', 587)
          
        # start TLS for security
        smtp_object.starttls()
          
        # Authentication
        smtp_object.login("YOUR EMAIL", "PASSWORD")
        subject = "GeeksforGeeks Umbrella Reminder"
        body = f"Take an umbrella before leaving the house.\
        Weather condition for today is {sky} and temperature is\
        {temperature} in {city}."
        msg = f"Subject:{subject}\n\n{body}\n\nRegards,\nGeeksforGeeks".encode(
            'utf-8')
          
        # sending the mail
        smtp_object.sendmail("FROM EMAIL",
                             "TO EMAIL", msg)
          
        # terminating the session
        smtp_object.quit()
        print("Email Sent!")
  
  
# Every day at 06:00AM time umbrellaReminder() is called.
schedule.every().day.at("06:00").do(umbrellaReminder)
  
while True:
    schedule.run_pending()


Output:

Sample Umbrella Reminder Email



Previous Article
Next Article

Similar Reads

Scraping Weather prediction Data using Python and BS4
This article revolves around scraping weather prediction d data using python and bs4 library. Let's checkout components used in the script - BeautifulSoup- It is a powerful Python library for pulling out data from HTML/XML files. It creates a parse tree for parsed pages that can be used to extract data from HTML/XML files. Requests - It is a Python
3 min read
Umbrella Activities in Software Engineering
Software engineering is a collection of interconnected phases. These steps are expressed or available in different ways in different software process models. Umbrella activities, such as project management, quality assurance, and documentation, support these phases, ensuring consistency, quality, and efficient progress throughout the development pr
4 min read
Birthday Reminder Application in Python
This app helps in reminding birthdays and notifying your friend's birthdays. This app uses Python and Ubuntu notifications to notify users on every startup of the system. # Python program For # Birthday Reminder Application # time module is must as reminder # is set with the help of dates import time # os module is used to notify user # using defau
2 min read
Get Live Weather Desktop Notifications Using Python
We know weather updates are how much important in our day-to-day life. So, We are introducing the logic and script with some easiest way to understand for everyone. Let’s see a simple Python script to show the live update for Weather information. Modules Needed In this script, we are using some libraries bs4: Beautiful Soup(bs4) is a Python library
2 min read
Scraping Indeed Job Data Using Python
In this article, we are going to see how to scrape Indeed job data using python. Here we will use Beautiful Soup and the request module to scrape the data. Module neededbs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in th
3 min read
Scraping data in network traffic using Python
In this article, we will learn how to scrap data in network traffic using Python. Modules Neededselenium: Selenium is a portable framework for controlling web browser.time: This module provides various time-related functions.json: This module is required to work with JSON data.browsermobproxy: This module helps us to get the HAR file from network t
5 min read
Clean Web Scraping Data Using clean-text in Python
If you like to play with API's or like to scrape data from various websites, you must've come around random annoying text, numbers, keywords that come around with data. Sometimes it can be really complicating and frustrating to clean scraped data to obtain the actual data that we want. In this article, we are going to explore a python library calle
2 min read
Scraping Flipkart Data using Python
Web scraping is commonly used to gather information from a webpage. Using this technique, we are able to extract a large amount of data and then save it. We can use this data at many places later according to our needs. For Scraping data, we need to import a few modules. These modules did not come with the Python package so we need to install these
3 min read
How to Extract Weather Data from Google in Python?
In this article, we will see how to extract weather data from google. Google does not have its own weather API, it fetches data from weather.com and shows it when you search on Google. So, we will scrape the data from Google, and also we will see another method to fetch a schematic depiction of a location's weather data for the next two days in Pyt
4 min read
How to not get caught while web scraping ?
In this article, we are going to discuss how to not get caught while web scraping. Let's look at all such alternatives in detail: Robots.txtIt is a text file created by the webmaster which tells the search engine crawlers which pages are allowed to be crawled by the bot, so it is better to respect robots.txt before scraping.Example: Here GFG's robo
5 min read
Python | Real time weather detection using Tkinter
Prerequisites : Introduction to tkinter | Find current weather of any cityPython offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest
5 min read
Create a Weather app using Flask | Python
Prerequisite : Flask installation Flask is a lightweight framework written in Python. It is lightweight because it does not require particular tools or libraries and allow rapid web development. today we will create a weather app using flask as a web framework. this weather web app will provide current weather updates of cities searched. Basic setu
2 min read
Weather app using Django | Python
In this tutorial, we will learn how to create a Weather app that uses Django as backend. Django provides a Python Web framework based web framework that allows rapid development and clean, pragmatic design. Basic Setup - Change directory to weather – cd weather Start the server - python manage.py runserver To check whether the server is running or
2 min read
Weather App in Python using Tkinter module
In this article, we are going to discuss how to create a weather app using tkinter. The GUI app will tell us the current weather of a particular city along with temperature details along with other details. Modules required:Tkinter: It is a built-in python library for making GUI using tkinter toolkit.Requests: It is a library which helps in fetchin
4 min read
Building A Weather CLI Using Python
Trying to know the weather is something that we all do, every day. But have you ever dreamed of making a tool on your own that can do the same? If yes, then this article is for you. In this article, we will look at a step-by-step guide on how to build a Weather CLI using OpenWeather API. What is OpenWeather API?OpenWeather API is a weather API prov
4 min read
Implementing Weather Forecast using Facade Design Pattern in Python
Facade Design Patterns are design patterns in Python that provide a simple interface to a complex subsystem. When we look into the world around us, we can always find facade design patterns. An automobile is the best example: you don't need to understand how the engine functions. To operate the engine, you are provided with a set of simple interfac
3 min read
Web Scraping Coronavirus Data into MS Excel
Prerequisites: Web Scraping using BeautifulSoup Coronavirus cases are increasing rapidly worldwide. This article will guide you on how to web scrape Coronavirus data and into Ms-excel. What is Web Scraping? If you’ve ever copy and pasted information from a website, you’ve performed the same function as any web scraper, only on a microscopic, manual
5 min read
Implementing web scraping using lxml in Python
Web scraping basically refers to fetching only some important piece of information from one or more websites. Every website has recognizable structure/pattern of HTML elements. Steps to perform web scraping :1. Send a link and get the response from the sent link 2. Then convert response object to a byte string. 3. Pass the byte string to 'fromstrin
3 min read
Newspaper scraping using Python and News API
There are mainly two ways to extract data from a website: Use the API of the website (if it exists). For example, Facebook has the Facebook Graph API which allows retrieval of data posted on Facebook.Access the HTML of the webpage and extract useful information/data from it. This technique is called web scraping or web harvesting or web data extrac
4 min read
Scraping COVID-19 statistics using Python and Selenium
Selenium is an open source web testing tool that allows users to test web applications across different browsers and platforms. It includes a plethora of software that developers can use to automate web applications including IDE, RC, webdriver and Selenium grid, which all serve different purposes. Moreover, it serves the purpose of scraping dynami
4 min read
Web Scraping CryptoCurrency price and storing it in MongoDB using Python
Let us see how to fetch history price in USD or BTC, traded volume and market cap for a given date range using Santiment API and storing the data into MongoDB collection. Python is a mature language and getting much used in the Cryptocurrency domain. MongoDB is a NoSQL database getting paired with Python in many projects which helps to hold details
4 min read
Scraping Television Rating Point using Python
In this article, We are going to write python scripts to scrape TRP(Television Rating Point) from BARC. TRP stands for Television Rating Point, It represents how many people watched which channels for how much time during a particular period. It is used to judge which television program is viewed most. Module needed:bs4: Beautiful Soup(bs4) is a Py
2 min read
Web scraping from Wikipedia using Python - A Complete Guide
In this article, you will learn various concepts of web scraping and get comfortable with scraping various types of websites and their data. The goal is to scrape data from the Wikipedia Home page and parse it through various web scraping techniques. You will be getting familiar with various web scraping techniques, python modules for web scraping,
9 min read
Quote Guessing Game using Web Scraping in Python
Prerequisite: BeautifulSoup Installation In this article, we will scrape a quote and details of the author from this site http//quotes.toscrape.com using python framework called BeautifulSoup and develop a guessing game using different data structures and algorithm. The user will be given 4 chances to guess the author of a famous quote, In every ch
3 min read
Scraping dynamic content using Python-Scrapy
Let's suppose we are reading some content from a source like websites, and we want to save that data on our device. We can copy the data in a notebook or notepad for reuse in future jobs. This way, we used scraping(if we didn't have a font or database, the form brute removes the data in documents, sites, and codes). But now there exist many tools f
4 min read
Scraping Reddit using Python
In this article, we are going to see how to scrape Reddit using Python, here we will be using python's PRAW (Python Reddit API Wrapper) module to scrape the data. Praw is an acronym Python Reddit API wrapper, it allows Reddit API through Python scripts. Installation To install PRAW, run the following commands on the command prompt: pip install praw
4 min read
Web Scraping Financial News Using Python
In this article, we will cover how to extract financial news seamlessly using Python. This financial news helps many traders in placing the trade in cryptocurrency, bitcoins, the stock markets, and many other global stock markets setting up of trading bot will help us to analyze the data. Thus all this can be done with the help of web scraping usin
3 min read
Pagination using Scrapy - Web Scraping with Python
Pagination using Scrapy. Web scraping is a technique to fetch information from websites. Scrapy is used as a Python framework for web scraping. Getting data from a normal website is easier, and can be just achieved by just pulling the HTML of the website and fetching data by filtering tags. But what is the case when there is Pagination in Python an
3 min read
Reading selected webpage content using Python Web Scraping
Prerequisite: Downloading files in Python, Web Scraping with BeautifulSoup We all know that Python is a very easy programming language but what makes it cool are the great number of open source library written for it. Requests is one of the most widely used library. It allows us to open any HTTP/HTTPS website and let us do any kind of stuff we norm
3 min read
Scraping And Finding Ordered Words In A Dictionary using Python
What are ordered words? An ordered word is a word in which the letters appear in alphabetic order. For example abbey & dirt. The rest of the words are unordered for example geeks The task at hand This task is taken from Rosetta Code and it is not as mundane as it sounds from the above description. To get a large number of words we will use an onlin
3 min read