Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading file from imgur using python directly via url

Tags:

python

bash

imgur

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?

like image 453
Yotam Avatar asked Mar 18 '26 13:03

Yotam


1 Answers

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)
like image 180
Schnouki Avatar answered Mar 21 '26 02:03

Schnouki