本文實例講述了Python實現周期性抓取網頁內容的方法。分享給大家供大家參考,具體如下:
1.使用sched模塊可以周期性地執行指定函數
2.在周期性執行指定函數中抓取指定網頁,并解析出想要的網頁內容,代碼中是六維論壇的在線人數
論壇在線人數統計代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#coding=utf-8 import time,sched,os,urllib2,re,string #初始化sched模塊的scheduler類 #第一個參數是一個可以返回時間戳的函數,第二個參數可以在定時未到達之前阻塞。 s = sched.scheduler(time.time,time.sleep) #被周期性調度觸發的函數 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四個參數分別為:間隔事件、優先級(用于同時間到達的兩個事件同時執行時定序)、被調用觸發的函數,給他的參數(注意:一定要以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程序設計有所幫助。