天地一沙鸥

[暴走零零漆的学习笔记]

原创 Python通过HTTP协议定期抓取文件收藏

新一篇: Python操作MySQL以及中文乱码的问题 | 旧一篇: 用Python发送邮件

可以扩充成为简单的抓取工具,定时抓取


#!usr/bin/python

import urllib2,time;
class ErrorHandler(urllib2.HTTPDefaultErrorHandler):
    
def http_error_default(self, req, fp, code, msg, headers):
        result 
= urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
        result.status 
= code
        
return result

URL
='http://www.ibm.com/developerworks/js/ajax1.js'
req
=urllib2.Request(URL)
mgr
=urllib2.build_opener(ErrorHandler())

while True:
    ns
=mgr.open(req)
    
if(ns.headers.has_key('last-modified')):
        modified
=ns.headers.get('last-modified')
    
if(ns.code==304):
        
print '''
          ==============================
              NOT MODIFIED
          ==============================
        
'''
    
elif(ns.code==200):
        
print ns.read()
    
else:
        
print 'there is an error';
        
    
if(not locals().has_key('modified')):
        modified
=time.time();
    req.add_header(
'If-Modified-Since',modified)
    time.sleep(
10)
 

发表于 @ 2007年07月26日 18:56:00|评论(loading...)|编辑

新一篇: Python操作MySQL以及中文乱码的问题 | 旧一篇: 用Python发送邮件

评论

#pythoner 发表于2007-07-29 06:58:56  IP: 10.13.23.*
python里面 httpcode==304的时候,也会抛出异常,觉得很不爽,还要自定义处理。
发表评论  


登录
Csdn Blog version 3.1a
Copyright © foyuan