python - 为使用 urllib.urlretrieve 下载的文件添加时间戳

标签 python urllib

我正在使用 urllib.urlretrieve 下载文件,我想添加一些内容以在下载前检查更改。我已经有如下内容:

import urllib

urllib.urlretrieve("http://www.site1.com/file.txt", r"output/file1.txt")
urllib.urlretrieve("http://www.site2.com/file.txt", r"output/file2.txt")

理想情况下,我希望脚本检查更改(比较上次修改的标记?),如果相同则忽略,如果更新则下载,我需要脚本为文件名添加时间戳。

有人能帮忙吗?

我是编程新手(python 是我的第一个)所以欢迎任何批评!

最佳答案

不幸的是,这在 Python 中似乎很难做到,因为您必须自己做所有事情。此外,urlretrieve 的界面不是很好。

以下代码应执行必要的步骤(如果文件存在则添加“If-Modified-Since” header 并调整下载文件的时间戳):

def download_file(url, local_filename):
    opener = urllib.request.build_opener()
    if os.path.isfile(local_filename):
        timestamp = os.path.getmtime(local_filename)
        timestr = time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(timestamp))
        opener.addheaders.append(("If-Modified-Since", timestr))
    urllib.request.install_opener(opener)
    try:
        local_filename, headers = urllib.request.urlretrieve(url, local_filename, reporthook=status_callback)
        if 'Last-Modified' in headers:
            mtime = calendar.timegm(time.strptime(headers['Last-Modified'], '%a, %d %b %Y %H:%M:%S GMT'))
            os.utime(local_filename, (mtime, mtime))
    except urllib.error.HTTPError as e:
        if e.code != 304:
            raise e
    urllib.request.install_opener(urllib.request.build_opener())  # Reset opener
    return local_filename

关于python - 为使用 urllib.urlretrieve 下载的文件添加时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16650608/

相关文章:

python - 如何在布洛赫球体上绘图时更改线宽

python - 从事件处理函数返回值 wxPython

python - Google http ://maps. google.com/maps/geo 非英文字符查询

python - 尝试一次通过搜索发送一个列表项

python - 跟踪自上次击键以来的时间?

python - 检查列表是否为空的最快方法是什么?在什么情况下一种方法优于另一种方法?

python - travis-ci build on Python3.4 六个 urllib 不会安装

python - 两个 Web 服务器(带 Django 的 Amazon EC2 和 Google App Engine)之间的安全通信

python - request.urlretrieve 在 PythonAnywhere 中作为计划任务运行时失败

python - 使用 Python 从 URL 下载图像给出损坏的结果