Pythonは定時に天気予報メールを送ります.

1910 ワード

python爬虫類の天気予報では、smatplibとemailモジュールを使ってメールボックスに送ることができます.scheduleモジュールを使ってタイミングよく送ることができます.コードは以下の通りです
#    
import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import schedule
import time

#       、           
account = str(input('          :'))
password = str(input('        :'))
receiver = str(input('          :'))

#       ,      
def weather_spider():
    #     :
    headers={
        'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
        }
    url='http://www.weather.com.cn/weather/101211001.shtml'
    #    :
    res=requests.get(url,headers=headers)
    res.encoding='utf-8'
    #    :
    soup=BeautifulSoup(res.text,'html.parser')
    #    :
    tem1= soup.find(class_='tem')
    weather1= soup.find(class_='wea')
    tem=tem1.text
    weather=weather1.text
    return tem,weather

#       
def send_email(tem,weather):
    global account,password,receiver
    mailhost='smtp.qq.com'
    qqmail = smtplib.SMTP()
    qqmail.connect(mailhost,25)
    qqmail.login(account,password)
    content= '      :
'+tem+weather message = MIMEText(content, 'plain', 'utf-8') subject = ' from python' message['Subject'] = Header(subject, 'utf-8') try: qqmail.sendmail(account, receiver, message.as_string()) print (' ') except: print (' ') qqmail.quit() # def job(): print(' ') tem,weather = weather_spider() send_email(tem,weather) print(' ') # schedule.every().day.at("7:00").do(job) while True: schedule.run_pending() time.sleep(1)