python- 如何正确地将 http GET 请求发送到不同的主机 IP 但同一主机

python- How to properly send http GET requests to different Host-IPs but same host

我正在尝试编写一个小脚本来向具有多个 IP 地址的主机发送 GET 请求。

到目前为止,我能够让脚本一次(同时)发送带有那些不同 IPs 的 GET 请求,有没有一种简单的方法可以做到这一点,所以我提供了 I 的列表Ps 它将使用 IP#1 发送请求,然后使用 IP#2 发送下一个请求,依此类推。

Ps:这里是完整的代码,所以你可以稍微理解我的要求,如果你想改进它,你也可以告诉我:)

感谢您的帮助! :D

#!/usr/bin/env python

import requests
import ujson
import time
import random


url = 'site'
headeR = {'Host': 'site.com'} 

while 1:


    hosts = ['X.X.X.235', 'X.X.X.94', 'X.X.X.191', 'X.X.X.247'] 
    cnt = 0
    while cnt<len(hosts):
      currentUrl = url.replace("site.com", hosts[cnt])
    cnt += 1
    r = requests.get(currentUrl , headers=headeR)
    listingInfoStr = r.content
    result= ujson.loads(listingInfoStr)
    listingInfoJson= result['listinginfo']  
    if listingInfoJson:
        for key, value in listingInfoJson.iteritems():
            #print("key %s, value %s" % (key, value))
            listingId = key
            try:
                subTotal = value["converted_price_per_unit"]
                feeAmount = value["converted_fee_per_unit"]
            except KeyError:
                continue
            totalPrice = subTotal + feeAmount
            totalPriceFloat = float(totalPrice) / 100
            print("listingId %s = [ %s + %s = %s ]" % (listingId, subTotal, feeAmount, totalPrice))
    else:
            print "Still Looking"
    time.sleep(25)

如果您可以向单个主机发出请求,那么很容易依次向不同的主机发出多个请求:

import time

def query_listing_info(hosts):
    for host in hosts:
        info = get_listing_info(host)
        if not info:
            print "Still looking"
        else:
            for listing_id, sub_total, fee_amount in parse_listing_info(info):
                total_price = sub_total + fee_amount
                print("listingId {listing_id} = [ {sub_total} + {fee_amount} = "
                      " {total_price} ]".format(**vars()))

hosts = ['x.x.x.x', 'y.y.y.y']
while 1:
    query_listing_info(hosts)
    time.sleep(25) # pause requests

其中 get_listing_info(host)host 发出单个请求:

import urlparse
import requests

parsed_url = urlparse.urlsplit('http://example.com/render/')
params = {'start': '0', 'count': '1', 'currency': '20', 'country': 'CDN'}

def get_listing_info(host): 
    url = urlparse.urlunsplit(parsed_url[:1] + (host,) + parsed_url[2:])
    r = requests.get(url, headers={'Host': parsed_url.netloc}, params=params)
    return r.json().get('listinginfo')

parse_listing_info(info)提取必要的信息:

def parse_listing_info(listing_info):
    for id, info in listinginfo.iteritems():
        try:
           yield id, info["converted_price_per_unit"], info["converted_fee_per_unit"]
        except KeyError:
           pass