在當今信息化時代,獲取實時天氣信息并自動發送給相關人員已經成為許多企業和個人的需求。本文將詳細介紹如何利用Python網絡爬蟲技術,結合郵件發送功能,實現自動發送天氣預告郵件的功能。
我們的目標是通過Python編寫一個腳本,能夠自動從天氣預報網站抓取最新的天氣信息,并將這些信息通過郵件發送給指定的收件人。
首先,我們需要安裝所需的Python庫??梢酝ㄟ^以下命令安裝:
pip install requests beautifulsoup4
為了能夠發送郵件,我們需要配置SMTP服務器。這里以Gmail為例:
選擇一個提供天氣預報的網站,例如中國天氣網(http://www.weather.com.cn/)。
使用requests
庫發送HTTP請求,獲取網頁內容。
import requests
url = "http://www.weather.com.cn/weather/101010100.shtml"
response = requests.get(url)
response.encoding = 'utf-8'
html_content = response.text
使用BeautifulSoup
庫解析HTML內容,提取所需的天氣信息。
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content, 'html.parser')
weather_info = soup.find('ul', class_='t clearfix').text
使用smtplib
庫配置SMTP服務器。
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 配置郵件服務器
mail_host = "smtp.gmail.com"
mail_port = 587
mail_user = "your_email@gmail.com"
mail_pass = "your_password"
# 創建郵件對象
msg = MIMEText(weather_info, 'plain', 'utf-8')
msg['From'] = Header(mail_user)
msg['To'] = Header("recipient_email@example.com")
msg['Subject'] = Header("每日天氣預告", 'utf-8')
使用SMTP服務器發送郵件。
try:
server = smtplib.SMTP(mail_host, mail_port)
server.starttls()
server.login(mail_user, mail_pass)
server.sendmail(mail_user, ["recipient_email@example.com"], msg.as_string())
print("郵件發送成功")
except smtplib.SMTPException as e:
print("郵件發送失敗:", e)
finally:
server.quit()
為了實現每天自動發送天氣預告郵件,可以使用cron
(Linux)或Task Scheduler
(Windows)來定時執行腳本。
將上述代碼整合成一個完整的Python腳本。
import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def get_weather():
url = "http://www.weather.com.cn/weather/101010100.shtml"
response = requests.get(url)
response.encoding = 'utf-8'
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
weather_info = soup.find('ul', class_='t clearfix').text
return weather_info
def send_email(weather_info):
mail_host = "smtp.gmail.com"
mail_port = 587
mail_user = "your_email@gmail.com"
mail_pass = "your_password"
msg = MIMEText(weather_info, 'plain', 'utf-8')
msg['From'] = Header(mail_user)
msg['To'] = Header("recipient_email@example.com")
msg['Subject'] = Header("每日天氣預告", 'utf-8')
try:
server = smtplib.SMTP(mail_host, mail_port)
server.starttls()
server.login(mail_user, mail_pass)
server.sendmail(mail_user, ["recipient_email@example.com"], msg.as_string())
print("郵件發送成功")
except smtplib.SMTPException as e:
print("郵件發送失敗:", e)
finally:
server.quit()
if __name__ == "__main__":
weather_info = get_weather()
send_email(weather_info)
通過本文的介紹,我們學習了如何利用Python網絡爬蟲技術從天氣預報網站抓取天氣信息,并通過SMTP服務器自動發送郵件。這一過程不僅提高了工作效率,還為日常生活中的信息獲取提供了便利。
希望本文能幫助你實現自動發送天氣預告郵件的功能,并為你的工作和生活帶來便利。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。