在之前吴氏私厨的基础上,每周五自动爬取下厨房本周最受欢迎的菜谱
1 import requests 2 import time 3 import schedule 4 import smtplib 5 from email.mime.text import MIMEText 6 from email.header import Header 7 from bs4 import BeautifulSoup 8 9 def caipu_fun(): 10 res = requests.get('http://www.xiachufang.com/explore/') 11 html = res.text 12 soup = BeautifulSoup(html,'html.parser') 13 item = soup.find('div',class_='info pure-u') 14 caipu = '本周最佳菜谱:' + item.find('a').text.strip() + '\n 链接: ' + 'http://www.xiachufang.com'+item.find('a')['href'] + '\n 原材料:' + item.find('p',class_='ing ellipsis').text.strip() 15 return caipu 16 17 def mail_fun(zhuti,caipu): 18 mail_user = 'www1707@xxx.cn' 19 mail_pwd = 'yyy' 20 receiver = 'user01@xxx.cn' 21 subject = zhuti 22 content = caipu 23 24 alimail = smtplib.SMTP() 25 alimail.connect('smtp.qiye.aliyun.com',25) 26 alimail.login(mail_user,mail_pwd) 27 28 message = MIMEText(content,'plain','utf-8') 29 message['Subject'] = Header(subject,'utf-8') 30 message['From'] = Header(mail_user,'utf-8') 31 message['To'] = Header(receiver,'utf-8') 32 33 alimail.sendmail(mail_user,receiver,message.as_string()) 34 alimail.quit() 35 36 def main_fun(): 37 zhuti = time.strftime('%Y{}%W{}').format('年 第','周 最佳菜谱') 38 caipu = caipu_fun() 39 mail_fun(zhuti,caipu) 40 print(zhuti) 41 42 schedule.every().friday.do(main_fun) 43 44 while True: 45 schedule.run_pending() 46 time.sleep(1)
老师的答案
1 import requests 2 import smtplib 3 import schedule 4 import time 5 from bs4 import BeautifulSoup 6 from email.mime.text import MIMEText 7 from email.header import Header 8 9 account = input('请输入你的邮箱:') 10 password = input('请输入你的密码:') 11 receiver = input('请输入收件人的邮箱:') 12 13 def recipe_spider(): 14 res_foods = requests.get('http://www.xiachufang.com/explore/') 15 bs_foods = BeautifulSoup(res_foods.text,'html.parser') 16 list_foods = bs_foods.find_all('div',class_='info pure-u') 17 list_all = '' 18 num=0 19 for food in list_foods: 20 num=num+1 21 tag_a = food.find('a') 22 name = tag_a.text.strip() 23 url = 'http://www.xiachufang.com'+tag_a['href'] 24 tag_p = food.find('p',class_='ing ellipsis') 25 ingredients = tag_p.text.strip() 26 food_info = ''' 27 序号: %s 28 菜名: %s 29 链接: %s 30 原料: %s 31 '''%(num,name,url,ingredients) 32 list_all=list_all+food_info 33 return(list_all) 34 35 def send_email(list_all): 36 global account,password,receiver 37 mailhost='smtp.qq.com' 38 qqmail = smtplib.SMTP() 39 qqmail.connect(mailhost,25) 40 qqmail.login(account,password) 41 content= '亲爱的,本周的热门菜谱如下'+list_all 42 message = MIMEText(content, 'plain', 'utf-8') 43 subject = '周末吃个啥' 44 message['Subject'] = Header(subject, 'utf-8') 45 try: 46 qqmail.sendmail(account, receiver, message.as_string()) 47 print ('邮件发送成功') 48 except: 49 print ('邮件发送失败') 50 qqmail.quit() 51 52 def job(): 53 print('开始一次任务') 54 list_all = recipe_spider() 55 send_email(list_all) 56 print('任务完成') 57 58 schedule.every().friday.at("18:00").do(job)#部署每周三的13:15执行函数的任务 59 60 while True: 61 schedule.run_pending() 62 time.sleep(1)