Yotam
Yotam

Reputation: 10685

Downloading file from imgur using python directly via url

Sometime, links to imgur are not given with the file extension. For example: http://imgur.com/rqCqA. I want to download the file and give it a known name or get it name inside a larger code. The problem is that I don't know the file type, so I don't know what extension to give it.

How can I achieve this in python or bash?

Upvotes: 2

Views: 7320

Answers (4)

Schnouki
Schnouki

Reputation: 7707

You should use the Imgur JSON API. Here's an example in Python, using requests:

import posixpath
import urllib.parse
import requests

url = "http://api.imgur.com/2/image/rqCqA.json"
r = requests.get(url)
img_url = r.json["image"]["links"]["original"]
fn = posixpath.basename(urllib.parse.urlsplit(img_url).path)

r = requests.get(img_url)
with open(fn, "wb") as f:
    f.write(r.content)

Upvotes: 7

inspectorG4dget
inspectorG4dget

Reputation: 113905

I've used this before to download tons of xkcd webcomics and it seems to work for this as well.

def saveImage(url, fpath):
    contents = urllib2.urlopen(url)
    f = open(fpath, 'w')
    f.write(contents.read())
    f.close()

Hope this helps

Upvotes: 3

JasonWyatt
JasonWyatt

Reputation: 5303

I just tried going to the following URLs:

And they all worked. It seems that Imgur stores several types of the same image - you can take your pick.

Upvotes: 3

Colleen
Colleen

Reputation: 25479

You can parse the source of the page using BeautifulSoup or similar and look for img tags with the photo hash in the src. With your example, the pic is

<img alt="" src="http://i.imgur.com/rqCqA.jpg" original-title="">

Upvotes: 0

Related Questions