26、自動爬取每日的天氣,並定時把天氣數據和穿衣提示發送到你的郵箱
阿新 • • 發佈:2019-05-12
The sch run parser ali pri mes use content 自動爬取每日的天氣,並定時把天氣數據和穿衣提示發送到你的郵箱。
之所以選擇這個相對樸實的爬蟲項目,是因為天氣每天都會有變化,那麽在學完這一關之後,不出意外,你就可以在明早收到天氣信息了。以此,親身體驗程序的作用。
你還可以把每日的天氣和溫馨的穿衣提示發送到你的戀人、家人、或朋友的郵箱裏,這也是傳遞心意的一種方式。
總體上來說,可以把這個程序分成三個功能塊:【爬蟲】+【郵件】+【定時】
1 import requests 2 import time 3 import schedule 4 from selenium import webdriver5 from bs4 import BeautifulSoup 6 import smtplib 7 from email.mime.text import MIMEText 8 from email.header import Header 9 10 def requests_fun(): 11 res = requests.get(‘http://www.weather.com.cn/weather1d/101010100.shtml‘) 12 res.encoding=‘utf-8‘ 13 soup = BeautifulSoup(res.text,‘html.parser‘) 14 tianqi = soup.find(‘input‘,id=‘hidden_title‘)[‘value‘] 15 chuanyi = soup.find(‘li‘,id=‘chuanyi‘).find(‘p‘).text 16 return (tianqi,chuanyi) 17 18 def selenium_fun(): 19 driver = webdriver.Chrome() 20 driver.get(‘http://www.weather.com.cn/weather1d/101010100.shtml‘) 21 time.sleep(2)22 tianqi = driver.find_element_by_id(‘hidden_title‘).get_attribute(‘value‘) 23 chuanyi = driver.find_element_by_id(‘chuanyi‘).find_element_by_tag_name(‘p‘).text 24 return str(tianqi,chuanyi) 25 driver.close() 26 27 def mail_fun(tianqi,chuanyi,zhuti): 28 mail_user = ‘[email protected]‘ 29 mail_pwd = ‘yyy‘ 30 receiver = ‘[email protected]‘ 31 subject = zhuti 32 content = tianqi+‘\t‘+chuanyi 33 34 alimail = smtplib.SMTP() 35 alimail.connect(‘smtp.qiye.aliyun.com‘,25) 36 alimail.login(mail_user,mail_pwd) 37 38 message = MIMEText(content,‘plain‘,‘utf-8‘) 39 message[‘Subject‘] = Header(subject,‘utf-8‘) 40 message[‘From‘] = Header(mail_user,‘utf-8‘) 41 message[‘To‘] = Header(receiver,‘utf-8‘) 42 43 alimail.sendmail(mail_user,receiver,message.as_string()) 44 alimail.quit() 45 46 def main_fun(): 47 tianqi,chuanyi = requests_fun() 48 zhuti = ‘天氣早知道 ‘+time.ctime() 49 mail_fun(tianqi,chuanyi,zhuti) 50 print(zhuti) 51 52 #requests_fun() 53 #selenium_fun() 54 #mail_fun() 55 #main_fun() 56 57 schedule.every(10).seconds.do(main_fun) 58 59 while True: 60 schedule.run_pending() 61 time.sleep(1)
26、自動爬取每日的天氣,並定時把天氣數據和穿衣提示發送到你的郵箱