Python通过变量循环处理多个get请求

2024-04-24 12:19:59 发布

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

我正试图在多个活动日期内获得门票

每个事件日期都有自己的eventID,因此对于23个可能的日期,eventID是1001-1023

我已经开始手动执行此操作,下面给出了给定日期的所有可用座位,但重复22次并不是最有效的方法

import requests
import json 

f = open('tickets.txt','a')

r = requests.get('https://www.website.com/events/1000/tickets/seatmap?sectionid=3')
d = json.loads(r.text)
zones = d['zones']
for key, value in zones.iteritems() :
    print >>f, (key, value)

我想通过eventid循环并一次打印所有日期的所有可用性。但是我在建立请求/URL时遇到了问题。到目前为止,我已经创造了:

eventIDs =  range(1001, 1023)
baseurl = "https://www.website.com/events/"
sectionId = "/tickets/seatmap?sectionId=3"

更新:我想我已经做到了,这个我认为有效

for i in eventIDs:
    url=baseurl+str(i)+sectionId
    r = requests.get(url) 
    d = json.loads(r.text)
    print >>f, (d)

这是最好的方法吗?非常感谢您的帮助。谢谢


Tags: 方法httpsimportcomjsongetwwwwebsite
1条回答
网友
1楼 · 发布于 2024-04-24 12:19:59

您应该考虑使rest调用异步。如果您想坚持requests-ish样式,可以使用^{}

# Python3
import grequests

event_ids =  range(1001, 1023)
base_url = "https://www.website.com/events/"
section_id = "/tickets/seatmap?sectionId=3"
# Create an array of urls
urls = [base_url + str(i) + section_id for i in event_ids ]
# Preapare requests
rs = (grequests.get(u) for u in urls)
# Send them
results = grequests.map(rs)

或者可以使用asyncio^{}。如果您对它感兴趣并想查看它的外观,可以访问this question

相关问题 更多 >