【问题标题】:python keep-alive connection and download imagepython keep-alive连接和下载图片
【发布时间】:2014-04-13 04:42:40
【问题描述】:

我需要通过 python 从站点下载图像,但该图像每秒更改一次。 可能吗: - 设置 python 连接 [keep-alive] - 下载图片;睡眠 1.5;下载图片;睡眠 1.5;下载图片;睡眠 1.5; - 关闭连接

我的意思是不会每 1.5 秒创建到站点的连接,而是使用一个保持活动连接。并在脚本末尾关闭连接(例如 15 秒后)。确保连接已关闭。

如果你有想法怎么做,请给我例子。谢谢!

【问题讨论】:

标签: python


【解决方案1】:

通过使用带有一些可选标志的requests library

import requests
r = requests.get(url='http://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg',stream=True)
print r.headers['last-modified']

有文件创建时间作为输出:

Thu, 03 Oct 2013 23:15:52 GMT

我们使用 'stream=True' 标志和 this description,因为:

此时只有响应标头已下载并且连接保持打开状态,因此允许我们将内容检索设为有条件

然后您可以检查新文件时间戳是否从旧时间戳更新,然后仅在文件更新时才下载。要下载文件,请使用 r.content:

image = r.content

这是一个工作代码:

import requests
import time
oldtime = ''
for i in xrange(100):
    r = requests.get(url='http://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg',stream=True)
    newtime = r.headers['last-modified']
    if newtime != oldtime:
        image = r.content
        oldtime = newtime
    # you can put your time.sleep() statement here, but it is not necessary

【讨论】:

  • 完美的代码,谢谢!但是我应该在代码末尾添加这一行吗? requests.get(url='upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg', headers={'Connection':'close'})
  • 这不是必需的,因为当程序停止时连接将关闭。如果您想明确关闭并重新打开连接,则需要包含它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 2014-03-07
  • 1970-01-01
相关资源
最近更新 更多