python - request.get 在循环时返回 400 响应——即使 URL 仍然相同

标签 python python-3.x python-requests

我尝试循环 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(),您将分别收到 404400 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/

相关文章:

visual-studio-2010 - Python 错误 : command '...\Microsoft Visual Studio 10.0\\VC\\BIN\\cl.exe' failed with exit status 2

python - 如何从Python中的二进制文件解析序列化的C结构?

python - SimpleCV:打开 Display() 时回溯错误

python - 如何使用父类中的对象最好地初始化子类的对象?

python tkinter 从命令中使用的函数返回值

Python - 如何阅读 Sharepoint excel 工作表特定工作表

python - 必须在您的浏览器中启用 Cookie [Python 请求]

python - 请求响应中的非 'ascii' 字符

python - 使用 Twitter 的 Streaming API 时更改 POST 请求参数

Python - 如何使用 'requests & BeautifulSoup' 抓取 Tr/Td 表数据