大家好,我是Python进阶者。
前言前几天国家四六级英语考试刚刚过去,考完后,有粉丝在群里吐槽,这次又得不到425分了。小编觉得,英语倒是没有那么难,只要多记单词,看英文就很easy了。正好这几天在Python交流群里边,【冫马讠成】大佬分享了一个有趣的代码,用于定时提醒用户记单词,觉得挺有意思,这里拿出来给大家分享。
实现思路实现思路倒是不难,其一是Python网络爬虫,将网页上的单词抓取到,中英文对照,然后存起来到一个变量中,其二是编写发送邮件的逻辑,编辑好邮寄模板,然后将抓到的内容发送出去即可。
实现过程这里直接上代码,如下所示:
from lxml import etree import requests import random import smtplib import schedule import time from bs4 import BeautifulSoup from email.mime.text import MIMEText from email.header import Header# account = input('请输入你的邮箱:') # password = input('请输入你的密码:') # receiver = input('请输入收件人的邮箱:') account = '{0}' .format('请输入你的邮箱:' ) password = '{0}' .format('请输入你的密码:' ) receiver = '{0}' .format('请输入收件人的邮箱:' ) def recipe_spider(): num = 0 list_all = '' words = [] meaning = [] choice = random.choice([(11, 226), (12, 105), (122, 35), (123, 25)]) url = "http://word.iciba.com/?action=words&class=" + str(choice[0]) + "&course=" + str( random.randint(1, choice[1])) r = requests.get(url) r.encoding = r.apparent_encoding if r.status_code == 200: text = r.text doc = etree.HTML(text) words = doc.xpath('//*[@class="word_main_list"]/li/div[@class="word_main_list_w"]/span//text()' ) meaning = doc.xpath('//*[@class="word_main_list"]/li/div[@class="word_main_list_s"]/span//text()' ) li = [] for i in range(len(words)): num += 1 n = '' ' %s、 %s %s ' '' % (num, words[i].strip(), meaning[i].strip()) list_all = list_all+n dic = {'words' : words[i], 'meaning' : meaning[i]} li.append(dic) print (li) return list_all def send_email(list_all): global account, password, receiver mailhost = 'smtp.qq.com' qqmail = smtplib.SMTP_SSL(mailhost, 465) #qqmail.connect(mailhost,465) qqmail.login(account, password) content = '亲爱的,今天记单词:' + list_all message = MIMEText(content, 'plain' , 'utf-8' ) subject = '今天记什么单词' message['Subject' ] = Header(subject, 'utf-8' ) try: qqmail.sendmail(account, receiver, message.as_string()) print ('邮件发送成功' ) except: print ('邮件发送失败' ) qqmail.quit() def job(): print ('开始一次任务' ) list_all = recipe_spider() send_email(list_all) print ('任务完成' )if __name__ == '__main__' : job()
你只需要输入你的邮箱,邮箱授权码和对应的收件人即可。如果不知道邮箱授权码怎么配置的话,请参考这篇文章:手把手教你使用Python网络爬虫实现邮件定时发送(附源码) 。上面有详细的配置过程,这里不再赘述。
代码运行之后,用户就可以收到你发送的邮件了,如下所示。
你也可以定时给自己发,使用定时任务工具,做个定时任务,每天提醒自己记单词,日积月累,这样你的四六级词汇就丰富啦!
总结大家好,我是Python进阶者。这篇文章主要基于Python网络爬虫和Python自动化办公中的邮件发送知识,实现自动发送邮件记单词的小项目。
最后感谢【冫马讠成】大佬的代码分享,也欢迎大家积极尝试,有好的内容也可以分享给我噢!