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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Python中的schedule模块和onedrive模块来实现定时抓取onedrive文件到本地文件夹。 首先需要安装schedule和onedrive模块,可以使用以下命令进行安装: ``` pip install schedule pip install onedrive-sdk-python ``` 接下来,你需要获得onedrive的API凭证,具体步骤可以参考Microsoft官方文档:https://docs.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/app-registration?view=odsp-graph-online 获取到API凭证后,你可以使用以下代码实现定时抓取onedrive文件到本地文件夹: ```python import schedule import time import os from onedrivesdk import ( OneDriveClient, http, AuthProvider ) # 定义抓取间隔时间(秒) INTERVAL = 60 * 10 # 定义本地文件夹路径和要抓取的onedrive文件路径 LOCAL_FOLDER_PATH = "D:/onedrive_files" ONEDRIVE_FILE_PATH = "/Documents/file.txt" # 定义onedrive API凭证信息 CLIENT_ID = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' CLIENT_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' REDIRECT_URI = 'http://localhost:8080' REFRESH_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 初始化auth_provider和client auth_provider = AuthProvider( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI, refresh_token=REFRESH_TOKEN ) client = OneDriveClient(auth_provider=auth_provider) def download_file(): # 获取onedrive文件的下载链接 item = client.item(path=ONEDRIVE_FILE_PATH) download_url = client.item(drive='me', id=item.id).get('@microsoft.graph.downloadUrl') # 下载文件到本地文件夹 response = http.get(download_url) file_name = os.path.basename(ONEDRIVE_FILE_PATH) with open(os.path.join(LOCAL_FOLDER_PATH, file_name), "wb") as f: f.write(response.content) print("File downloaded successfully!") schedule.every(INTERVAL).seconds.do(download_file) while True: schedule.run_pending() time.sleep(1) ``` 以上代码定义了定时抓取间隔时间、本地文件夹路径、要抓取的onedrive文件路径以及API凭证信息。在`download_file`函数中,首先使用`client.item`方法获取onedrive文件的信息,然后使用`client.item(drive='me', id=item.id).get('@microsoft.graph.downloadUrl')`方法获取文件的下载链接,最后使用`http.get`方法下载文件到本地文件夹。 如果你想要抓取其他类型的文件,只需要将`ONEDRIVE_FILE_PATH`更改为相应的路径即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值