美文网首页
python爬虫入门之监控教务处网站

python爬虫入门之监控教务处网站

作者: 森先生_wood | 来源:发表于2015-10-26 23:09 被阅读1007次

    一个简单的爬虫,主要分为两部分,一是从网页上抓取源代码,二是从这些代码中提取出想要的内容。前者我用的是Requests库,比起自带的urllib库要简单方便,需要自行安装。后者我暂时用re的正则表达式,虽然有时候会出现一点莫名其妙的小问题。

    下面是Requests库和re的一些简单常用的方法。

    (1)从目标网址直接抓取源代码

    html=requests.get(url) 
    

    (2)将源代码格式转化成可以处理的格式

    text=html.text
    content=html.content//偶尔会用到
    

    (3)寻找内容

    resout=re.findall("开始(.*?)结束",text,re.S)//返回一个列表
    resout=re.search("开始(.*?)中间(.*?)结束",text,re.S)
    resout.group(1)            resout.group(2)`
    

    接下来接收一下我的思路:首先从教务网上爬取下来首页上的通知,将它们保存在txt文件里。然后就是一定时间间隔的循环,每次爬取下来之后都与文件里的内容比较,一旦发现不同,说明有新通知,发送邮件至我的邮箱(这一部分代码直接网上搜来的)

    源代码如下:
    #--coding:utf8--
    '''爬虫监控教务处网站,有新公告则发送邮件到邮箱,绑定的手机接到短信提示
    缺点:一开始运行的话,如果出现撤销置顶的情况,旧的消息会出现在首页
    解决方式:手动输入前两页的信息,或者运行一段时间'''
    import smtplib
    from email.mime.text import MIMEText
    import requests
    import re
    import os
    import time
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')

    class mailhelper(object):
        '''
        这个类实现发送邮件的功能
        '''
        def __init__(self):
    
            self.mail_host="smtp.163.com"
            self.mail_user="发送邮箱账号如sss2397472"
            self.mail_pass="发送邮箱密码"
            self.mail_postfix="163.com"
    
        def send_mail(self,to_list,sub,content):
            me="教务网助手"+"  <"+self.mail_user+"@"+self.mail_postfix+">"
            msg = MIMEText(content,_subtype='plain',_charset='utf-8')
            msg['Subject'] = sub
            msg['From'] = me
            msg['To'] = ";".join(to_list)
            try:
                server = smtplib.SMTP()
                server.connect(self.mail_host)
                server.login(self.mail_user,self.mail_pass)
                server.sendmail(me, to_list, msg.as_string())
                server.close()
                return True
            except Exception, e:
                print str(e)
                return False
    
    class jiaowu(object):
        '''
        这个类实现将爬取教务网公告内容
        '''
        def __init__(self):
            self.url = 'http://jw.nju.edu.cn/'
        def getContent(self):
            html = requests.get(self.url).text
            text=re.search('<div class="con1">(.*?) </div>',html,re.S).group(1)
            title=re.findall("title='(.*?)'>",text,re.S)
            href=re.findall("<a href='(.*?)'",text,re.S)
            content=[]
            for i in range(0,8):
                content.append(title[i]+'点此打开链接:jw.nju.edu.cn/'+href[i])
            return content
        def tocheck(self,content):
            if not os.path.exists('resout.txt'):
                f= open('resout.txt','a')
                for each in content:
                    f.write(each + '\n')
                f.close()
                print'初始化成功'
            else:
                f = open('resout.txt', 'r')
                existweibo = f.readlines()
                i=0
                for each in content:
                    if each + '\n' in existweibo:
                        pass
                    else:
                        helper.tosave(each)
                        i=1
                if i==0:
                    print 'pass'
                f.close()
        def tosave(self,text):
            if mailhelper().send_mail(mailto_list,u'教务网有新消息',text):
                print u"发送成功"
            else:
                print u"发送失败"
            print text
            f= open('resout.txt','a')
            f.write(text + '\n')
            f.close()
    
    if __name__ == '__main__':
        mailto_list=['收件邮箱账号@163.com']
        helper = jiaowu()
        while True:
            content = helper.getContent()
            helper.tocheck(content)
            time.sleep(5)`

    相关文章

      网友评论

          本文标题:python爬虫入门之监控教务处网站

          本文链接:https://www.haomeiwen.com/subject/vasxhttx.html