首页 > 解决方案 > 如何使用文件导入 python 请求以输出状态码

问题描述

我是 Python(3) 的新手,所以请不要抨击我:D

我正在使用以下代码来导入包含不同 URL 的 .txt 文件,以便检查它们的状态代码。在我的示例中,我添加了 4 个站点 URL

这是只有一个 URL 的 import.txt:

https://site1.site
https://site2.site
https://site3.site
https://site4.site
https://site5.site

虽然这是 py 脚本本身:

import requests
with open('import.txt', 'r') as f :
 for line in f :
  print(line)
#try :
 r = requests.get(line)
 print(r.status_code)
#except requests.ConnectionError :
#    print("failed to connect")

这是回应:

https://site1.site

https://site2.site

https://site3.site

https://site4.site

https://site5.site

400

即使 site3 和 site4 是 301,而 site5 有连接失败的响应,我只收到适用于所有提交的 URL 的 400 响应。

如果我使用以下脚本为这些 URL 中的每一个请求.head,那么我会收到正确的页面状态代码(以下示例中的“永久移动”)。这是单个请求脚本:

import requests
try:
    r = requests.head("http://site3.net/")
    if r.status_code == 200:
        print('Success!')
    elif r.status_code == 301:
        print('Moved Permanently')
    elif r.status_code == 404:
        print('Not Found')
#    print(r.status_code)
except requests.ConnectionError:
    print("failed to connect")

感谢从 URL 获取 HTTP 响应代码的最佳方法是什么?

标签: pythonpython-3.xpython-requestshttp-status-codes

解决方案


您的调用requests.get()for循环之外,因此只执行一次。尝试缩进相关行,如下所示:

import requests
with open('import;txt', 'r') as f :
 for line in f :
  print(line)
#try :
  r = requests.get(line)
  print(r.status_code)
#except requests.ConnectionError :
#    print("failed to connect")

附言。我建议您使用 4 空格缩进。这样,这样的错误就更容易被发现。


推荐阅读