使用Python实现每日一句英语发送到手机

目标:通过使用Python中的requests、BeautifulSoup、snmp库实现发送每日一句英文到手机短信。

思路:这还要从中国移动的邮箱说起,忘了什么时候开始,139邮箱每次收到一封邮件的时候,就会给我发送一封短信,告诉我邮件的大体内容,开始的时候是很烦的,几乎从来不会收到短息的我,想把这个推送关掉的,但是,后来想想,这不就相当于一个短信网关(国内可是几乎没有免费的)了嘛,我可以凭这个给自己发短信呀,然后做个定时任务,或者干些其他的事~~~balabala,说做就做吧……

使用的网站:http://dict.cn       http://www.dailyenglishquote.com/      其实网站都无所谓了,只要是能够每日更新的就好。

使用requests库获取网站页面,使用BeautifulSoup进行网页解析,使用smtplib库实现邮件的发送,发送至139邮箱即可。

邮件内容获取代码如下:

# !/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup
from collections import Iterable

api_url = "http://dict.cn/"
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
                  '(KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}

response = requests.get(api_url, headers=headers)
soup1 = BeautifulSoup(response.content, 'lxml')
bc = soup1.find_all('img')
for i in bc:
    try:
        print(i['audio'])
        audio_index = i
    except Exception as e:
        pass
    finally:
        print(i['src'])

abc = audio_index.parent.get_text()
print(abc)

邮件发送代码如下:

# !/usr/bin/env python3
# -*- coding: utf-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.header import Header

mail_host = "smtp.yahoo.com"
mail_user = "[email protected]"
mail_pass = "balabalabala"

sender = '[email protected]'
receivers = ['[email protected]']

msg = MIMEText("Please call me.", 'plain', 'utf-8')
msg['From'] = Header('请查看附件内容!', 'utf-8')
msg['TO'] = Header('请查看附件内容!', 'utf-8')

subject = 'What are you doing now, if you have some time, please call me. xiao'
msg['Subject'] = Header(subject, 'utf-8')

try:
    smtpobj = smtplib.SMTP()
    smtpobj.connect(mail_host, 25)
    smtpobj.login(mail_user, mail_pass)
    smtpobj.sendmail(sender, receivers, msg.as_string())
    print('success')
except smtplib.SMTPException as e:
    print('error')
    print(e)

Python 中使用BeautifulSoup时一定要注意,官方推荐的解析器为lxml。

每次写代码的时候总会遇到的编码问题,这次再次给我出了一个难题,于是写了另外的一篇博客来记录,在Python中有关编码的那些坑。

博客地址如下:http://blog.csdn.net/wswit/article/details/63253371

你可能感兴趣的:(python)