【问题标题】:Fetch all pages using python request使用 python 请求获取所有页面
【发布时间】:2023-03-06 23:46:01
【问题描述】:

我正在使用 api 从网站获取订单。问题是它一次只能获取 20 个订单。我发现我需要使用分页迭代器,但不知道要使用它。如何一次获取所有订单。

我的代码:

def search_orders(self):
    headers = {'Authorization':'Bearer %s' % self.token,'Content-Type':'application/json',}
    url = "https://api.flipkart.net/sellers/orders/search"
    filter = {"filter": {"states": ["APPROVED","PACKED"],},}
    return requests.post(url, data=json.dumps(filter), headers=headers)

这是一个文档链接。

Documentation

【问题讨论】:

    标签: python pagination python-requests


    【解决方案1】:

    你需要按照文档的建议去做 -

    对搜索 API 的第一次调用会根据 pageSize 值返回有限数量的结果。 调用响应的 nextPageURL 字段返回的 URL 获取搜索结果的后续页面。

    nextPageUrl - 字符串 - 对此 URL 的 GET 调用获取下一页结果。最后一页不存在

    (强调我的)

    您可以使用response.json() 来获取响应的json。然后你可以检查标志 - hasMore - 看看是否还有更多,如果有,使用 requests.get() 获取下一页的响应,并继续这样做直到 hasMore 为假。示例 -

    def search_orders(self):
        headers = {'Authorization':'Bearer %s' % self.token,'Content-Type':'application/json',}
        url = "https://api.flipkart.net/sellers/orders/search"
        filter = {"filter": {"states": ["APPROVED","PACKED"],},}
        s = requests.Session()
        response = s.post(url, data=json.dumps(filter), headers=headers)
        orderList = []
        resp_json = response.json()
        orderList.append(resp_json["orderItems"])
        while resp_json.get('hasMore') == True:
            response = s.get('"https://api.flipkart.net/sellers{0}'.format(resp_json['nextPageUrl']))
            resp_json = response.json()
            orderList.append(resp_json["orderItems"])
        return orderList
    

    上面的代码应该返回完整的订单列表。

    【讨论】:

    • “也许你的意思是 http://{0}?”.format(url)) requests.exceptions.MissingSchema:无效的 URL 给出了这个错误
    • 哦,好的,抱歉,由于没有所需的信息来进行邮局电话,因此无法对此进行测试。在我的回答中更新了它。
    • raise InvalidURL("无效 URL %r: 未提供主机" % url)
    • 尝试打印 resp_json.get('hasMore')resp_json['nextPageUrl'] ,它给出了什么?
    • 也试试我给出的最新代码,resp_json.get('hasMore') 可能会返回一个字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2015-08-04
    • 2021-12-25
    • 2016-04-10
    • 1970-01-01
    相关资源
    最近更新 更多