python - 如何使用文件导入 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")
解决方案
您的调用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 空格缩进。这样,这样的错误就更容易被发现。
推荐阅读
- android - 在我的动画列表中颤动改变图标 onTap
- java - 使用新创建的项目返回到以前的活动时更新 recyclerView 适配器
- jquery - 带有 setTimeout 的 jQuery 函数动画运行一次
- android - 如何在新平台重新提交应用以供审核?
- c# - Umbraco - 从文本而不是 nodeId 获取内容
- python-3.x - 有没有办法打开一个封闭的 Image 对象?
- java - 获取二叉树特定级别的所有节点
- javascript - 我的待办事项列表 Javascript 代码不会将我想要的样式存储在数组中
- html - 此自定义 HTML 代码的联系表单字段
- node.js - gcloud 功能部署不上传 html 和 css