2021-07-27 爬取教育类网站的新闻列表,发送邮件,并转化为exe文件

爬取芥末堆网站的新闻列表!
非常简单的一段代码,待完善。

import requests
import datetime,time
import smtplib
import redis
from email.header import Header
from email.mime.text import MIMEText
#from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import datetime,time
proxies1={"http":"http://39.100.106.237:8002"}
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36','Referer':'https://www.jiemodui.com/'}


def send_mail(html):  # 发送邮件函数
    sender = '[email protected]'
    receivers = ['[email protected]','[email protected]','[email protected]','[email protected]','[email protected]'] #收件人邮箱列表
    sender_pass = '???????'  # 第三方授权码,非登录密码,不要泄露
    msg = MIMEMultipart('mixed')
    # 邮件添加的头尾信息等
    msg['From'] = '芥末堆教育新闻'  # 芥末堆新闻列表
    # msg['To'] = 'James'  # 邮件的主题,显示在接收邮件的预览页面
    subject = '芥末堆教育新闻' +'  '+ time.strftime("%Y-%m-%d %H:%M:%S")
    msg['subject'] = Header(subject, 'utf-8')
    text_info = html
    text_sub = MIMEText(text_info, 'html', 'utf-8')
    msg.attach(text_sub)
    try:
        sftp_obj = smtplib.SMTP('smtp.qq.com', 25)
        sftp_obj.login(sender, sender_pass)
        for email in receivers:
            sftp_obj.sendmail(sender, email, msg.as_string())
        sftp_obj.quit()
        print('最新的芥末堆教育新闻已经发至邮箱%s'%receivers)
    except Exception as e:
        for i in range(3):
            print('sendemail failed. Reason:')
            print(e)

class Jiemodui():  
    def __init__(self):
        self.rs_conn=redis.Redis(host="localhost", port='6379', db=0, password='???????', decode_responses=True)  # redis数据库连接
    def crawler(self):
        print("现在时间是:",datetime.datetime.today())
        print('1秒后开始抓取芥末堆的新闻列表:')
        time.sleep(1)
        newsqty=0 #记录新闻数
        message='' #记录邮件内容
        for page in range(1,3):
            url0='https://www.jiemodui.com/Api/Index/news?p=' #后面加页数
            url=url0+str(page)
            html=requests.get(url,headers=headers,proxies=proxies1)
            # print(html.status_code)
            # print(html.json())
            json=html.json()
            newslist=json['list']
            for i in newslist:
                newspage='https://www.jiemodui.com/N/'+i['id'] +'.html'
                # print(i['name'],'  ',i['utime'],'  ',newspage)  #newspage 是新闻详情链接                
                if self.rs_conn.sadd('newsid', i['id']):  # 如果能插入,表示为新的新闻
                    newsqty+=1
                    print(i['name'],'  ',i['utime'],'  ',newspage)  #newspage 是新闻详情链接
                    message += '<tr><td>%s</td><td>%s</td><td><a href=%s>%s</a></td></tr>' % (i['name'],i['utime'],newspage,newspage) #仅发送新的新闻至邮箱
                    # self.rs_conn.hset(i['id'],'Topic',i['name'])
                    # self.rs_conn.hset(i['id'],'Published Time',i['utime'])
                    # self.rs_conn.hset(i['id'],'Link',newspage)
        print('共爬取最新的新闻数:',newsqty)
        return message

if __name__=='__main__':
    t1=time.time()
    T=Jiemodui()
    try:
        message=T.crawler()
        if message !='':
            message = '<html><head><title>芥末堆教育新闻</title></head><body><table border=1 cellspacing=1>' + '<tr><td>新闻标题</td><td>发布时间</td><td>链接地址</td></tr>' + message + '</table></body></html>'
            send_mail(message) #发送邮件
            # print(message)
    except Exception as e:
        print('爬取失败,原因是:','\n',e)
    print('time cost: ', time.time()-t1)

转化为exe文件步骤:

1、安装pyinstaller
打开cmd,输入 pip install pyinstaller

2、进入python源文件所在的目录,
然后使用命令:pyinstaller -F jiemodui.py
其中-F表示一个文件。
会在当前目录得到一个 dict 文件夹,里面就会有一个名为jiemodui.exe 的文件。

3、双击执行exe文件即可看到结果。
 

猜你喜欢

转载自blog.csdn.net/weixin_45387160/article/details/119143453