每天爬取黄金价格,并自动发送到邮箱

每天爬取http://www.sge.com.cn/(上海黄金交易所)的黄金价格,并自动发送到邮箱

# -*- coding: utf-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.header import Header
import urllib.request
import re
import datetime


#黄金网站
url = "http://www.sge.com.cn/"

def url_open(url):
    try:
        headers=("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0")
        opener=urllib.request.build_opener()
        opener.addheaders=[headers]
        urllib.request.install_opener(opener)
        data=urllib.request.urlopen(url).read().decode("utf-8","ignore")
        return data
    except:
        pass

def get_today():
    h=datetime.datetime.now()
    today=h.strftime("%Y-%m-%d")    
    return today

def get_gold():
    try:
        fileName='gold_price.txt'
        message=''
        data=url_open(url)
        today_date=get_today()

        pat1='<span class="fl color999">((.*?))'
        pat2='<span class="colorRed fs24">(.+?)<'

        statis_time=re.compile(pat1).findall(data)[0]
        today_price=re.compile(pat2).findall(data)[0]

        with open(fileName,'a+') as fh:
            fh.write("日期:"+today_date+"\t"+statis_time+"\t"+"早盘价:"+today_price+"\n")

        message=statis_time+"的黄金价格为:"+str(today_price)
        return message
    except:
        return "无法获取到黄金价格信息"



def mail_qq(subject,content):
    mail_host="smtp.qq.com"#设置服务器
    mail_user="[email protected]"#用户名
    mail_pass="fobbaybdiubfgjhd"#密码
    sender="[email protected]"
    receivers=['[email protected]']#接收邮件
    try:
        message=MIMEText(content,'plain','utf-8')
        message['From']=Header("小平",'utf-8')#发件人昵称
        message['To']=Header("小平",'utf-8')#收件人昵称

        message['Subject']=Header(subject,'utf-8')

        server=smtplib.SMTP_SSL(mail_host,465)
        server.login(mail_user,mail_pass)
        server.sendmail(sender,receivers,message.as_string())

        server.quit()#关闭链接
        print("邮件发送成功")
    except Exception as e:
        print(e)
        print("邮件发送失败")


if __name__=="__main__":
    subject=get_gold()
    today_data=get_today()
    content="今天是"+today_data+","+subject
    print(content)
    mail_qq(subject,content)


猜你喜欢

转载自blog.csdn.net/d1240673769/article/details/80430129