26、自动爬取每日的天气,并定时把天气数据和穿衣提示发送到你的邮箱
自动爬取每日的天气,并定时把天气数据和穿衣提示发送到你的邮箱。
之所以选择这个相对朴实的爬虫项目,是因为天气每天都会有变化,那么在学完这一关之后,不出意外,你就可以在明早收到天气信息了。以此,亲身体验程序的作用。
你还可以把每日的天气和温馨的穿衣提示发送到你的恋人、家人、或朋友的邮箱里,这也是传递心意的一种方式。
总体上来说,可以把这个程序分成三个功能块:【爬虫】+【邮件】+【定时】
1 import requests 2 import time 3 import schedule 4 from selenium import webdriver 5 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 = 'www1707@xxx.cn' 29 mail_pwd = 'yyy' 30 receiver = 'user01@xxx.cn' 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)