【问题标题】:How to import python requests using a file in order to output the status code如何使用文件导入 python 请求以输出状态码
【发布时间】:2019-12-07 12:28:00
【问题描述】:

我是 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")

感谢What’s the best way to get an HTTP response code from a URL?

【问题讨论】:

    标签: python python-3.x python-requests http-status-codes


    【解决方案1】:

    您对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 空格缩进。这样一来,这样的错误就更容易被发现了。

    【讨论】:

    • 非常感谢您的回答,它奏效了 :) 我立即尝试使用 Python,所以您指出了一个事实;我需要先学习基础知识,空格缩进绝对是其中之一。
    • 我建议您使用 Python 官方文档中的 The Python Tutorial
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 2019-12-15
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多