有没有更快的方法来循环遍历python中的get请求页面?

时间:2018-05-12 04:05:47

标签: python json api web-scraping get

我希望从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)

1 个答案:

答案 0 :(得分:0)

您可以尝试使用scrapy。 您需要创建一个蜘蛛,在设置中,您可以修改CONCURRENT_REQUESTS。它会更快。如果您还没有使用scrapy,我建议您从以下链接开始https://doc.scrapy.org/en/latest/intro/tutorial.html

相关问题