【发布时间】: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