Python实现周期性抓取网页内容的方法
2015-11-04 00:00
901 查看
本文实例讲述了Python实现周期性抓取网页内容的方法。分享给大家供大家参考,具体如下:
1.使用sched模块可以周期性地执行指定函数
2.在周期性执行指定函数中抓取指定网页,并解析出想要的网页内容,代码中是六维论坛的在线人数
论坛在线人数统计代码:
#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程序设计有所帮助。
相关文章推荐
- Python IDE PyCharm的基本快捷键和配置简介
- python logging 模块使用详解
- Python列表中包含中文时输出十六进制转中文的小方法
- 使用python访问网站遇到的问题
- 在arm上使用python-2.7.10
- python3 与 python2的 区别比较
- Learning Python
- Python核心编程读笔 1
- Windows下安装Flask
- Python easy_install安装插件错误(UnicodeDecodeError)解决办法
- python与数据库
- 小甲鱼:Python学习笔记001_变量_分支_数据类型_运算符等基础
- python正则表达式
- 搜索引擎数据源爬取——python scrapy
- Python的输入和输出以及流程控制语句
- python PIL读取图像转换为灰度图及另存为其它格式(也可批量改格式)
- [LeetCode]题解(python):044-Wildcard Matching
- python-PIL学习笔记
- [python] 时间序列分析之ARIMA
- [LeetCode]题解(python):043-Multiply Strings