从IMDB id列表下载电影海报

2024-09-28 05:27:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用IMDB ID下载电影列表的海报。我使用的是MovieLens数据集(https://grouplens.org/datasets/movielens/latest/)。在

我在网上找到了一个例子,但是,这段代码下载了1部电影(https://gist.github.com/baderj/7414775)的所有可用海报

我如何调整这一点,以便只下载列表中每部电影的最高评级海报(即1张海报)?在

我知道我可以通过以下方式访问最高级别的海报:

posters = api_response['posters'][0]

我知道我可以通过以下方式下载图像URL列表:

^{pr2}$

但是,我不知道如何修改函数get_poster_url来做我想要的。在

提供了完整的脚本:

import os
import requests

CONFIG_PATTERN = 'http://api.themoviedb.org/3/configuration?api_key= 
IMG_PATTERN = 'http://api.themoviedb.org/3/movie/{imdbid}/images?api_key={key}' 
KEY = '<your_api_key>'

def _get_json(url):
    r = requests.get(url)
    return r.json()

def _download_images(urls, path='.'):
"""download all images in list 'urls' to 'path' """

    for nr, url in enumerate(urls):
        r = requests.get(url)
        filetype = r.headers['content-type'].split('/')[-1]
        filename = 'poster_{0}.{1}'.format(nr+1,filetype)
        filepath = os.path.join(path, filename)
        with open(filepath,'wb') as w:
            w.write(r.content)

我知道我必须修改这个部分来获得一个id列表的url列表。在

def get_poster_urls(imdbid):
    """ return image urls of posters for IMDB id
        returns all poster images from 'themoviedb.org'. Uses the
        maximum available size. 
        Args:
            imdbid (str): IMDB id of the movie
        Returns:
            list: list of urls to the images
    """
    config = _get_json(CONFIG_PATTERN.format(key=KEY))
    base_url = config['images']['base_url']
    sizes = config['images']['poster_sizes']

    """
        'sizes' should be sorted in ascending order, so
            max_size = sizes[-1]
        should get the largest size as well.        
    """
    def size_str_to_int(x):
        return float("inf") if x == 'original' else int(x[1:])
    max_size = max(sizes, key=size_str_to_int)

    posters = _get_json(IMG_PATTERN.format(key=KEY,imdbid=imdbid))['posters']
    poster_urls = []
    for poster in posters:
        rel_path = poster['file_path']
        url = "{0}{1}{2}".format(base_url, max_size, rel_path)
        poster_urls.append(url) 

    return poster_urls

def tmdb_posters(imdbid, count=None, outpath='.'):    
    urls = get_poster_urls(imdbid)
    if count is not None:
        urls = urls[:count]
    _download_images(urls, outpath)

我知道我必须修改这个部分来获取一个列表而不是一个IMDB ID

if __name__=="__main__":
    tmdb_posters('tt0095016')

Tags: pathkeyapiurl列表sizegetdef

热门问题