python如何正确地将httpget请求发送到不同的主机但是同一hos

2024-10-03 02:35:16 发布

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

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

到目前为止,我能够让脚本一次(同时)用这些不同的IP发送GET请求,有没有一种简单的方法让它提供IP列表,然后它用IP#1发送请求,然后用IP#2发送下一个请求,等等。。在

Ps:这是完整的代码,这样您可以理解我的要求,如果您想改进它,也可以让我知道:)

谢谢你的帮助!:天

#!/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)

Tags: keyimportip脚本getvaluesiteprint
1条回答
网友
1楼 · 发布于 2024-10-03 02:35:16

如果您可以向单个主机发出请求,则可以依次向不同主机发出多个请求:

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发出单个请求:

^{pr2}$

并且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

相关问题 更多 >