python请求多个URL的REST API

时间:2014-09-19 00:13:43

标签: python

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

结尾的网址

我尝试使用github.com/ross/requests-futures,但未能将其投入使用

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:找不到连接适配器

我基本上要做的是下面的代码:

url = "http://www.ecommerce.com/stores?serviceTypes=-1&storeIds=1"
url2 = "http://www.ecommerce.com/stores?serviceTypes=-1&storeIds=2"
url3 = "http://www.ecommerce.com/stores?serviceTypes=-1&storeIds=3"
header = {
    'access_token': '12341234',
    'country_code': 'US',
    'language_code': 'en'}
r = requests.get(url, headers=header)
r2 = requests.get(url2, headers=header)
r3 = requests.get(url3, headers=header)

dump = r.text + r2.text + r3.text

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

1 个答案:

答案 0 :(得分:0)

您是否尝试动态创建网址并发出请求?您可以使用计数器变量动态创建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错误,请确保您的网址格式正确。

相关问题