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

使用python爬取网页发送到邮箱

2017-08-01 12:30 344 查看
py3.6;

#coding:utf-8   #强制使用utf-8编码格式
import smtplib  #加载smtplib模块
from email.mime.text import MIMEText
from email.utils import formataddr
import requests
from bs4 import BeautifulSoup
import arrow
my_sender='xxx@163.com' #发件人邮箱账号,为了后面易于维护,所以写成了变量
my_user='xxx@qq.com' #收件人邮箱账号,为了后面易于维护,所以写成了变量

'''
爬取数据
'''
##########################################################################################
def get_msg():
url1 = 'https://www.jubi.com/gonggao/'
webdata1 = requests.get(url1).text
soup1 = BeautifulSoup(webdata1, 'lxml')
new_title1 = soup1.select("div.new_list > ul > li > a.title")
for n in new_title1:
title1 = n.get_text()
break
url2 = 'https://www.jubi.com/btc/'
webdata2 = requests.get(url2).text
soup2 = BeautifulSoup(webdata2, 'lxml')
new_title2 = soup2.select("div.new_list > ul > li > a.title")
for n in new_title2:
title2 = n.get_text()
break
url3 = 'https://www.jubi.com/shanzhaibi/'
webdata3 = requests.get(url3).text
soup3 = BeautifulSoup(webdata3, 'lxml')
new_title3 = soup3.select("div.new_list > ul > li > a.title")
for n in new_title3:
title3 = n.get_text()
break
hashaki = title1 + '\n' + title2 + '\n' + title3
return hashaki
#######################################################################################
def mail(hashaki):
ret=True
    try:
msg=MIMEText(hashaki,'plain','utf-8')
msg['From']=formataddr(["邮箱名字",my_sender])   #括号里的对应发件人邮箱昵称、发件人邮箱账号
msg['To']=formataddr(["CCH陈常鸿",my_user])   #括号里的对应收件人邮箱昵称、收件人邮箱账号
msg['Subject']="hashaki" #邮件的主题,也可以说是标题

server=smtplib.SMTP("smtp.163.com",25)  #发件人邮箱中的SMTP服务器,端口是25
server.login(my_sender,"xxx")    #括号中对应的是发件人邮箱账号、邮箱密码
server.sendmail(my_sender,[my_user,],msg.as_string())   #括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
server.quit()   #这句是关闭连接的意思
except Exception:   #如果try中的语句没有执行,则会执行下面的ret=False
ret=False
    return ret
if __name__ == "__main__":
last_hashaki = get_msg()
do = "已经链接"
ret1 = mail(do)
if ret1:
print("成功")
while(1):
time = arrow.now().minute
if time == 30:
hashaki = get_msg()
if hashaki != last_hashaki:
ret=mail(hashaki)
if ret:
print("成功") #如果发送成功则会返回ok,稍等20秒左右就可以收到邮件
else:
print("失败")  #如果发送失败则会返回filed
last_hashaki = hashaki
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python url 邮箱