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

发布于 2021-01-29 15:04:02

我想知道为什么当我这样依次调用request.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)

我对所有请求的状态都良好,但是当我在for循环中执行该状态时,例如:

for word in fIn :
        response = requests.get(url.format(word))
        if(response.status_code == 200):
            print "OK"
        else:
            print(response.status_code)
            print "Error"
            print word

除最后一个请求外,所有请求我都得到400(错误)。

附加信息:SO上有一个相关的问题,其中提到了两种应对这种情况的方法:等待,标题。
在我的情况下
以及标题中,wait不起作用-我不知道在那里提供了什么。

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

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)
关注者
0
被浏览
116
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您需要 删除 尾随的换行符:

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

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看