如何在循环中发出多个请求的Python requests模块?

2024-03-28 16:06:07 发布

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

我不知道为什么我打电话来请求.get()结果是这样的:

response = requests.get(url.format("set"))
print(response.status_code)
response = requests.get(url.format("map"))
print(response.status_code)
response = requests.get(url.format("list"))
print(response.status_code)
response = requests.get(url.format("vector"))
print(response.status_code)
response = requests.get(url.format("string"))
print(response.status_code)

所有请求的状态都是OK,但在for循环中执行时,比如:

^{pr2}$

除了最后一个请求,我得到了400(错误)。在

附加信息: 这里有related question on SO,这里提到了两种处理这种情况的方法:等待,标题。
在我的情况下,等待不起作用
关于标题-我不知道该提供什么。在

更新: 我正在尝试实现的特定版本:

from lxml import html

import requests

fOut = open("descriptions.txt","w")

with open('dummyWords.txt') as fIn:
    for word in fIn :
        print word
        response = requests.get(url.format(word))
        if(response.status_code == 200):
            print "OK"
        else:
            print(response.status_code)
            print(word)

Tags: importformaturl标题forgetresponsestatus
2条回答

您需要去除的尾随新行:

with open('dummyWords.txt') as fIn:
    for word in map(str.strip, fIn) :

它适用于最后一个单词,因为文件中最后一个单词的末尾显然没有新行。"www.foo.com\n"与{}不同

编码后的数据解决了我的问题。在

cmd = urllib.quote(cmds[i])

对于我的测试用例

  • 不需要换行符
  • 无需睡眠时间

相关问题 更多 >