使用Python抓取天气数据以在电子邮件上获得雨伞提醒
在本文中,我们将了解如何使用Python抓取天气数据并通过电子邮件获取提醒。如果天气条件是下雨或多云,该程序会向您发送“雨伞提醒”到您的电子邮件,提醒您在离开家之前收拾好雨伞。我们将使用 bs4 和Python中的请求库从谷歌抓取天气信息。
然后根据天气情况,我们将使用 smtplib 库发送电子邮件。为了每天在指定时间运行这个程序,我们将使用Python中的 schedule 库。
需要的模块
- bs4 : Beautiful Soup (bs4) 是一个Python库,用于从 HTML 和 XML 文件中提取数据。要安装此库,请在 IDE/终端中键入以下命令。
pip install bs4
- 要求: 该库允许您非常轻松地发送 HTTP/1.1 请求。要安装此库,请在 IDE/终端中键入以下命令。
pip install requests
- smtplib: smtplib 是一个Python模块,它定义了一个 SMTP 客户端会话对象,可用于向 Internet 上的任何机器发送邮件。要安装此库,请在 IDE/终端中键入以下命令。
pip install smtplib
- 日程表:日程表是一个Python库,用于在一天中的特定时间或一周中的特定天安排任务。要安装此库,请在 IDE/终端中键入以下命令。
pip install schedule
分步实施
第 1 步:导入 schedule、smtplib、requests 和 bs4 库。
Python3
import schedule
import smtplib
import requests
from bs4 import BeautifulSoup
Python3
city = "Hyderabad"
url = "https://www.google.com/search?q=" + "weather" + city
html = requests.get(url).content
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]
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)
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!")
Python3
# Every day at 06:00AM time umbrellaReminder() is called.
schedule.every().day.at("06:00").do(umbrellaReminder)
while True:
schedule.run_pending()
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()
第 2 步:创建具有指定城市名称的 URL,并创建绕过此 URL 的请求实例。
蟒蛇3
city = "Hyderabad"
url = "https://www.google.com/search?q=" + "weather" + city
html = requests.get(url).content
第 3 步:将检索到的 HTML 文档传递给 Beautiful Soup,它将返回一个去除了 HTML 标签和元数据的字符串。使用 find函数,我们将检索所有必要的数据。
蟒蛇3
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]
第 4 步:如果天气状况变成下雨或多云,该程序将向收件人发送一封带有“雨伞提醒”消息的电子邮件。为了封装 SMTP 连接,我创建了一个 SMTP 对象,参数为 `smtp.gmail.com` 和 587。创建 SMTP 对象后,您可以使用您的电子邮件地址和密码登录。
注意:不同的网站使用不同的端口号。在本文中,我们使用 Gmail 帐户发送电子邮件。这里使用的端口号是“587”。如果您想使用 Gmail 以外的网站发送邮件,则需要获取相应的信息。
蟒蛇3
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)
第 5 步:出于安全原因,SMTP 连接现在处于 TLS 模式。传输层安全加密所有 SMTP 命令。之后,出于身份验证目的,您需要在登录实例中传递您的 Gmail 帐户凭据。如果您输入无效的电子邮件 ID 或密码,编译器将显示身份验证错误。
将您需要发送的消息保存到一个变量中,例如 msg。使用 sendmail() 实例发送您的消息。 sendmail() 使用三个参数:sender_email_id、receiver_email_id 和 message_to_be_sent。这三个参数的顺序必须相同。这将从您的帐户发送一封电子邮件。完成任务后,使用quit()结束SMTP会话。
蟒蛇3
# 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!")
第六步:使用日程库,每天在特定时间安排任务。 schedule.run_pending() 检查计划任务是否正在等待运行。
蟒蛇3
# Every day at 06:00AM time umbrellaReminder() is called.
schedule.every().day.at("06:00").do(umbrellaReminder)
while True:
schedule.run_pending()
注意:当你执行这个程序时,它会向你抛出一个 smtplib.SMTPAuthenticationError 并且还会向你的电子邮件发送一个严重的安全警报,因为简而言之,谷歌不允许你通过 smtplib 登录,因为它已经标记了这种登录因为“不太安全”,所以你要做的就是在你登录到你的谷歌帐户时转到这个链接,并允许访问:
下面是完整的实现:
蟒蛇3
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()
输出:
Umbrella 提醒电子邮件示例