您的位置:首页 > 编程语言 > Python开发

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

2017-03-17 12:21 771 查看
目标:通过使用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 = "balabala@yahoo.com"
mail_pass = "balabalabala"

sender = 'balabala@yahoo.com'
receivers = ['test@163.com']

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 requests应用