How do I save a GIF from a url?

6.5k Views Asked by At

I'm using Giphypop to retrieve the url of a gif. I saved this url in a variable for convenience, but now I need to somehow save the gif to file. But I'm getting an error.

I think this can be reopened. My problem is Windows not opening the gif file after saving. Here is the code and a screenshot of the problem, sorry I couldn't post earlier.

Code:

import giphypop
from urllib import request

g = giphypop.Giphy()

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

Screenshot:

enter image description here

3

There are 3 best solutions below

1
On

Try this:

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

Once you have a URL, it's as simple as a single line (and an import, to be fair):

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

If you are not a fan of urllib, you can try using the requests module:

import requests

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

Or you also can try using a shorter alternative to the code above:

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")