【问题标题】:How do I save a GIF from a url? [duplicate]如何从 url 保存 GIF? [复制]
【发布时间】:2017-05-17 16:45:38
【问题描述】:

我正在使用Giphypop 来检索gif 的网址。为了方便起见,我将此 url 保存在一个变量中,但现在我需要以某种方式将 gif 保存到文件中。但我遇到了一个错误。

我认为这可以重新打开。我的问题是 Windows 在保存后没有打开 gif 文件。这是问题的代码和屏幕截图,抱歉我不能早点发布。

代码:

import giphypop
from urllib import request

g = giphypop.Giphy()

request.urlretrieve("http://giphy.com/gifs/fullerhouse-3oz8xJfB6XGBwOA8HS", "test.gif")

截图:

【问题讨论】:

  • Windows 10 有没有告诉你为什么打不开?您是否验证下载的文件是否确实是 GIF?如果您以其他方式下载文件,Windows 10 可以打开文件吗? (另外,你的代码在哪里???????)
  • @RadLexus 现在,Windows 只是说“我们无法打开文件”。没有有用的细节。如果我以正常方式下载它,我很确定 Windows 能够正确打开它,我只是想学习如何通过脚本来完成所有这些操作。
  • 请提供更多细节。这太宽泛了
  • @frlan 哪一部分不清楚?我有一个 gif 的 url,我需要使用脚本将其下载并保存到我的硬盘中。
  • 您应该提供您用来保存文件的脚本,否则我们将无法为您提供帮助

标签: python gif giphy giphy-api


【解决方案1】:

如果你不是 urllib 的粉丝,你可以尝试使用 requests 模块:

import requests

url = "http://www.url.of/the-file/here.gif"
response = requests.get(url)
data = response.text
open("./image.gif", "w").write(data)

或者您也可以尝试使用上述代码的更短的替代方案:

import requests

download = lambda url, filename="": open(filename if filename else (url.split("/")[-1] or "file.html"), "w").write(requests.get(url).text)
download("http://www.url.of/the-file/here.gif", "image.gif")

【讨论】:

    【解决方案2】:

    试试这个:

    import urllib
    foo = urllib.urlretrieve('htttp://www.somelink.com/file.gif','localfilename.gif')
    

    【讨论】:

    • 被穆雷尼克秒杀
    【解决方案3】:

    一旦你有了一个 URL,它就像一行一样简单(公平地说,还有一个导入):

    import urllib
    urllib.urlretrieve('http://example.com/somefile.gif', '/path/to/save/myfile.gif')
    

    【讨论】:

    • 这正是我昨晚尝试的,但Windows只是说它无法打开它。几个小时后我回家时会仔细检查。你确定这适用于 GIF 吗?我看到了一个使用它但用于图像的示例。
    • @whatwhatwhat 这肯定有效。如果您有具体问题,则必须分享更多详细信息(例如您遇到的错误)
    • 代码: urllib.urlretrieve(http://giphy.com/gifs/fullerhouse-3oz8xJfB6XGBwOA8HS', 'test.gif') 错误: Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'urllib' has no attribute 'urlretrieve'
    • @whatwhatwhat 你用的是什么python版本?
    • 我使用的是 3.5.2 版
    猜你喜欢
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2014-02-05
    • 1970-01-01
    • 2015-11-18
    • 2016-01-08
    • 2010-12-23
    相关资源
    最近更新 更多