Python實現周期性抓取網頁內容的方法
更新時間:2015年11月04日 15:22:07 作者:intergret
這篇文章主要介紹了Python實現周期性抓取網頁內容的方法,涉及Python時間函數及正則匹配的相關操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了Python實現周期性抓取網頁內容的方法。分享給大家供大家參考,具體如下:
1.使用sched模塊可以周期性地執(zhí)行指定函數
2.在周期性執(zhí)行指定函數中抓取指定網頁,并解析出想要的網頁內容,代碼中是六維論壇的在線人數
論壇在線人數統(tǒng)計代碼:
#coding=utf-8 import time,sched,os,urllib2,re,string #初始化sched模塊的scheduler類 #第一個參數是一個可以返回時間戳的函數,第二個參數可以在定時未到達之前阻塞。 s = sched.scheduler(time.time,time.sleep) #被周期性調度觸發(fā)的函數 def event_func(): req = urllib2.Request('http://bt.neu6.edu.cn/') response = urllib2.urlopen(req) rawdata = response.read() response.close() usernump = re.compile(r'總計 <em>.*?</em> 人在線') usernummatch = usernump.findall(rawdata) if usernummatch: currentnum=usernummatch[0] currentnum=currentnum[string.index(currentnum,'>')+1:string.rindex(currentnum,'<')] print "Current Time:",time.strftime('%Y,%m,%d,%H,%M',time.localtime(time.time())),'User num:',currentnum # 保存結果,供圖表工具amcharts使用 result=open('liuvUserNUm','a') result.write('{year: new Date('+time.strftime('%Y,%m,%d,%H,%M',time.localtime(time.time()))+'),value:'+currentnum+'},\n') result.close() #enter四個參數分別為:間隔事件、優(yōu)先級(用于同時間到達的兩個事件同時執(zhí)行時定序)、被調用觸發(fā)的函數,給他的參數(注意:一定要以tuple給如,如果只有一個參數就(xx,)) def perform(inc): s.enter(inc,0,perform,(inc,)) event_func() def mymain(inc=900): s.enter(0,0,perform,(inc,)) s.run() if __name__ == "__main__": mymain()
希望本文所述對大家Python程序設計有所幫助。
相關文章
淺析python打包工具distutils、setuptools
python包在開發(fā)中十分常見,一般的使用套路是所有的功能做一個python模塊包,打包模塊,然后發(fā)布,安裝使用。這篇文章給大家介紹了python打包工具distutils、setuptools的相關知識,感興趣的朋友一起看看吧2018-04-04Python中map,reduce,filter和sorted函數的使用方法
這篇文章主要介紹了Python中map,reduce,filter和sorted函數的使用方法,是Python入門學習中的基礎知識,需要的朋友可以參考下2015-08-08