【问题标题】:Is there a faster way to loop through the pages of a get request in python?有没有更快的方法来循环在 python 中获取请求的页面?
【发布时间】:2018-05-12 04:05:46
【问题描述】:

我想从 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)

【问题讨论】:

    标签: python json api web-scraping get


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-05
      • 2018-07-25
      • 2019-07-29
      • 2022-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多