我尝试循环 URL 列表来获取所有页面的图像 URL。但是,当使用循环时,请求返回 400。当我测试单个 URL 时,它有效(200)。自第一次调用以来失败。
尝试添加时间延迟但仍然不起作用。
f = open(url_file)
lineList = f.readlines()
print(lineList[0]) # Test
i = 1
for url in lineList:
print(url) # Test -- the url is the same as lineList[0] above
res = requests.get(url) # works when copied the printed url in but not as a variable
预期 200 -- 错误给出 400
最佳答案
说明
如果您的 url_file
使用换行符(\n
字符)作为行分隔符,则可能会导致服务器响应不稳定。这是因为 f.readlines()
不会自动从每行末尾删除 \n
。有些服务器会忽略 URL 中的此字符并返回 200 OK
,有些则不会。
例如:
f = open(r"C:\data\1.txt") # text file with newline as line separator
list_of_urls = f.readlines()
print(list_of_urls)
输出
['https://habr.com/en/users/\n', 'https://stackoverflow.com/users\n']
如果您在上面这些确切的 URL 上运行 requests.get()
,您将分别收到 404
和 400
HTTP 状态代码。如果末尾没有 \n
,它们就是有效的现有网页 - 您可以自己检查。
您没有注意到代码中这些额外的 \n
,因为您在 每个项目 上使用了 print()
,但没有显示此内容符号“明确”为 \n
。
如何修复
使用 splitlines()
而不是 readlines()
来删除末尾的 \n
:
import requests
with open(url_file) as f:
list_of_urls = f.read().splitlines() # read file without line delimiters
for url in list_of_urls:
res = requests.get(url)
print(res.status_code)
关于python - request.get 在循环时返回 400 响应——即使 URL 仍然相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56900350/