我想使用IMDB ID下载海报以获取电影列表。我正在使用MovieLens数据集(https://grouplens.org/datasets/movielens/latest/)。
我在网上找到了一个示例,但是,此代码下载了一部电影(https://gist.github.com/baderj/7414775)的所有可用海报
我该如何调整以仅下载列表中每部电影收视率最高的海报(即1张海报)?
我知道我可以通过以下方式访问获得最高评价的海报:
posters = api_response['posters'][0]
我知道我可以通过以下方式下载图像网址列表:
for i in test_urls:
if __name__=="__main__":
tmdb_posters(i)
但是,我不知道如何修改函数get_poster_urls来完成我想要的工作。
提供了完整的脚本:
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')