如何使用文件导入python请求以输出状态代码
我是Python(3)新手,所以请不要抨击我:D 我使用以下代码来导入一个包含不同URL的.txt文件,以便检查它们的状态代码。 在我的示例中,我添加了4个站点URL 以下是仅包含一个URL的import.txt:如何使用文件导入python请求以输出状态代码,python,python-3.x,python-requests,http-status-codes,Python,Python 3.x,Python Requests,Http Status Codes,我是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.tx
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")
感谢您对
请求的调用。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文档中学习。