From bd0b224b8566742e7507a2bfb20857c258e5970f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Alberto=20Orejuela=20Garc=C3=ADa?= Date: Fri, 16 Aug 2019 19:32:49 +0200 Subject: [PATCH] Download and save video It checks the media type and download accordingly. --- Pipfile | 1 + Pipfile.lock | 10 +++++++++- api.py | 18 +++++++++++++----- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/Pipfile b/Pipfile index 60888d7..f50102f 100644 --- a/Pipfile +++ b/Pipfile @@ -8,6 +8,7 @@ verify_ssl = true [packages] configparser = "*" requests = "*" +youtube-dl = "*" [requires] python_version = "3.7" diff --git a/Pipfile.lock b/Pipfile.lock index 36c4a89..f7b9fd1 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -1,7 +1,7 @@ { "_meta": { "hash": { - "sha256": "e345781a1d6882db32363ca2f62c6c6f27ef534b49b7e3361e859d1e4e596067" + "sha256": "73772dd96e3e2d59447bf352706f2fba46223342938b2f8c3144d678929e6b09" }, "pipfile-spec": 6, "requires": { @@ -59,6 +59,14 @@ "sha256:dbe59173209418ae49d485b87d1681aefa36252ee85884c31346debd19463232" ], "version": "==1.25.3" + }, + "youtube-dl": { + "hashes": [ + "sha256:f0831d15eec48e980c9bc00657ede5e21775d463db2d0af9f6ba482225d6c2bf", + "sha256:ff65a10f81b64d8e0d1872a89bee0d075370ba6e4c658193e56e6f93e5ca46ba" + ], + "index": "pypi", + "version": "==2019.8.13" } }, "develop": {} diff --git a/api.py b/api.py index 6490a98..49cc026 100644 --- a/api.py +++ b/api.py @@ -15,6 +15,7 @@ import configparser import requests +import youtube_dl config = configparser.ConfigParser() config.read('config.cfg') @@ -25,8 +26,15 @@ payload = {'api_key': api_key} r = requests.get(baseurl, params = payload) api_response = r.json() -r = requests.get(api_response['hdurl']) -filename = 'data/' + api_response['date'] + '.jpg' -with open(filename, 'wb') as f: - for chunk in r.iter_content(chunk_size=128): - f.write(chunk) +filename = 'data/' + api_response['date'] +if api_response['media_type'] == 'image': + r = requests.get(api_response['hdurl']) + filename = filename + '.jpg' + with open(filename, 'wb') as f: + for chunk in r.iter_content(chunk_size=128): + f.write(chunk) +elif api_response['media_type'] == 'video': + filename = filename + '.%(ext)s' + ydl_opts = {'outtmpl': filename} + with youtube_dl.YoutubeDL(ydl_opts) as ydl: + ydl.download([api_response['url']]) -- 2.45.2