Python实现周期性抓取网页内容的方法

作者:intergret 时间:2023-04-12 01:33:36 

本文实例讲述了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,抓取,网页
0
投稿

猜你喜欢

  • python重试装饰器示例

    2022-07-28 10:03:12
  • asp中设置session过期时间方法总结

    2013-06-01 19:52:04
  • Python语言编写电脑时间自动同步小工具

    2023-12-23 20:46:08
  • python复制文件代码实现

    2022-08-29 09:28:11
  • 设计哲学与跨界

    2009-08-18 12:25:00
  • PHP 应用容器化以及部署方法

    2023-11-14 15:45:06
  • Python字符串拼接的4种方法实例

    2023-01-30 18:57:15
  • Flask 入门系列 Cookie与session的介绍

    2022-06-21 00:45:44
  • 不成熟的标准化是我们唯一惧怕的

    2008-08-15 18:55:00
  • Safari参考样式库之webkit

    2009-07-26 09:50:00
  • python 以16进制打印输出的方法

    2023-10-23 07:33:17
  • Python实现免费音乐下载器

    2023-12-26 23:51:16
  • 全网最细 Python 格式化输出用法讲解(推荐)

    2021-07-15 12:01:32
  • PHP简易延时队列的实现流程详解

    2023-05-29 23:02:48
  • JupyterLab远程密码访问实现

    2022-06-04 23:52:26
  • Python安装第三方库及常见问题处理方法汇总

    2022-11-22 04:40:51
  • Python魔术方法详解

    2022-04-25 00:13:05
  • Python多线程同步Lock、RLock、Semaphore、Event实例

    2023-08-03 20:47:15
  • Python NLP开发之实现聊天机器人

    2021-12-21 18:04:48
  • opencv-python 开发环境的安装、配置教程详解

    2022-04-25 22:14:58
  • asp之家 网络编程 m.aspxhome.com