用于多个URL的python请求REST API

2024-10-03 02:43:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过做项目自学python,并尝试为商店位置请求一个API。有6000家商店,但API一次只允许一个位置。正如您在下面我的代码中看到的,它不是非常有效。请求1-6000个URL的更有效方法是什么?对于从http://www.ecommerce.com/stores?serviceTypes=-1&storeIds=1开始到http://www.ecommerce.com/stores?serviceTypes=-1&storeIds=6000结束的URL

我试着用github.com/ross/requests-但没能让它发挥作用

import requests, json
from requests import Session

session = Session()
url = ['http://www.ecommerce.com/stores?serviceTypes=-1&storeIds=%s' % n for n in xrange(1, 6000)]

header = {
    'access_token': '12341234',
    'country_code': 'US',
    'language_code': 'en'}
r = session.get(url, headers=header)

dump = r.text

f = open("myfile.txt", "w")
f.write(dump)

当前我收到以下错误:requests.exceptions.InvalidSchema:找不到连接适配器

我实际上要做的是下面的代码:

^{pr2}$

Tags: 代码importcomapihttpurlsessionwww
1条回答
网友
1楼 · 发布于 2024-10-03 02:43:17

你试过动态创建网址和发出请求吗?您可以使用计数器变量创建URL并动态发出请求:

header = {
    'access_token': '12341234',
    'country_code': 'US',
    'language_code': 'en'}

for i in range(0, 6001):
    url = "http://www.ecommerce.com/stores?serviceTypes=-1&storeIds=" + str(i)
    r = requests.get(url, headers=header)
    # Do what you want with r.text here

根据API的请求限制,在发出所有这些请求时可能会遇到问题。在

至于InvalidSchema错误,请确保您的URL格式正确。在

相关问题 更多 >