Python code to download video thumbnail from Dailymotion

  • Post category:Algorithms

Youtube and Dailymotion are the two biggest video hosting websites that provide embed code to show videos on any website. If you want to host some videos, you do not have to worry about buying a server or a VPS. You can upload your videos to one of these hosting platforms and get the embed code to show your videos on any website. Now, if you want to download the thumbnail of any video hosted on Dailymotion, there are several ways. However, using their API is the preferred option. Dailymotion provides thumbnails of three different sizes: large, medium, and small. You can pass the size of the thumbnail to the API as an argument. The argument can be one of these values: thumbnail_large_url, thumbnail_medium_url, thumbnail_small_url.

In this post, I am providing a Python code to fetch the video thumbnail from Dailymotion. You need to know the video_id of the video whose thumbnail you want to download. The video_id can be found in the URL of the video.

E.g. In this URL “https://www.dailymotion.com/video/x79m15w”, the video_id is “x79m15w”.

import urllib.request
import requests
import json


def fetch_img_link(id, headers):
    """
    Get the URL of the thumbnail from dailymotion api
    """
    url = "https://api.dailymotion.com/video/" + id + "?fields=thumbnail_large_url"
    request = urllib.request.Request(url, None, headers)
    response = urllib.request.urlopen(request)
    json_data = json.loads(response.read())
    return json_data['thumbnail_large_url']


def save_image_file(ilink, filename, headers):
    response = requests.get(ilink, headers=headers)
    if response.status_code == 200:
        with open(filename, 'wb') as f:
            f.write(response.content)
    else:
        print("Bad response code :", response.status_code)


# START OF THE CODE #
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
hdrs = {'User-Agent': user_agent, }
video_id = "x79m15w"
flname = "dm_x79m15w.jpg"
dm_path = fetch_img_link(video_id, hdrs)
save_image_file(dm_path, flname, hdrs)

The above code will download the thumbnail of video “x79m15w” and will save it as “dm_x79m15w.jpg”.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.