[英]Is there a faster way to loop through the pages of a get request in python?
我想从2017年12月发布的themoviedb.org api中获取所有电视节目ID。大约有3676页的json数据。 我可以在每个api请求中访问一个页面。 因此,要遍历3676页数据,我必须在循环中进行大量的api请求,这需要花费大量时间。 有没有一种更快的方法来避免循环,从而获得2017年12月发布的所有电视节目ID? 下面是我在python中的代码:
import requests
import json
#tv urls
baseTvUrl = 'http://api.themoviedb.org/3/discover/tv?release_date.gte=2017-12-01&release_date.lte=2017-12-31&' + api_key
baseCreditUrlTv = 'https://api.themoviedb.org/3/tv/'
baseCreditUrl2 = '/credits?' + api_key
myResponseTv = requests.get(baseTvUrl)
if(myResponseTv.ok):
Data = json.loads(myResponseTv.content.decode('utf-8'))
total_pages_tv = Data['total_pages']
tv_ids = {*()}
print(total_pages_tv)
#Method to get all the tv id's by iterating through all the pages
for page in range(total_pages_tv):
page = page+1
#print(page)
tvUrlPage = baseTvUrl + '&page=' + str(page)
myResponseTv = requests.get(tvUrlPage)
if(myResponseTv.ok):
Data = json.loads(myResponseTv.content.decode('utf-8'))
for results in Data['results']:
if(results is not None):
#print(type(results))
for key, value in results.items():
if(key=='id'):
#print(key, 'is:', value)
tv_ids.add(value)
print(tv_ids)
您可以尝试使用scrapy。 您需要创建蜘蛛,然后在设置中可以修改CONCURRENT_REQUESTS
。 它会更快。 如果您还没有使用scrapy,建议您从以下链接开始:https: //doc.scrapy.org/en/latest/intro/tutorial.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.