python - 使用请求和 HTTP/HTTPS 简化 Python v3.X 代码
问题描述
我在 Python 3.7 中有以下代码。本质上,我有一个包含许多以http://开头的 URL 的列表。我的代码的目的是:-
- 使用 requests.head() 检查 URL 是否正常
- 如果它不返回 200 状态,
http
请在url变量中替换为https
- 使用 requests.head() 检查 URL 现在是否使用 https
- 如果它没有返回 200 状态,请继续到列表中的下一个 URL
import requests
my_list = [#Lots of URLs in this list]
for url in my_list:
r = requests.head(url)
if r.status_code==200:
print("website %s is up" % url)
else:
print("URL %s is not accessible" % url)
url = url.replace('http', 'https')
print("Now trying URL %s" % url)
r = requests.head(url, headers=headers)
if r.status_code==200:
print("website using HTTPS %s is up" % url)
else:
print("website %s is still not accessible" % url)
我的代码看起来效率不高。我正在考虑查看 requests.head() 的某种功能,以便我现在重复它,但我仍然觉得必须有一种更有效的方式来执行上述操作。
有什么建议么?该requests
模块是否有任何可以设置为检查 HTTP 和 HTTPS 的选项?我在网上找不到任何东西
解决方案
Multithreading
import requests
def worker(url):
r = requests.head(url)
if r.status_code==200:
print("website %s is up" % url)
else:
print("URL %s is not accessible" % url)
url = url.replace('http', 'https')
print("Now trying URL %s" % url)
r = requests.head(url, headers=headers)
if r.status_code==200:
print("website using HTTPS %s is up" % url)
else:
print("website %s is still not accessible" % url)
from _thread import start_new_thread
for url in list_of_your_url:
start_new_thread(worker,(url,))
推荐阅读
- r - 在 AWS SageMaker R 内核上反序列化模型对象
- javascript - 在 Preact 中渲染原始 HTML 而不使用 Preact 标记?
- google-maps - Can We Restrict Google Maps NearbySearch to Not Return Specific Type?
- python-3.x - 更新嵌套列表中的特定元素时,整个列表都会更新
- reactjs - Material UI Version 0.20 到 v4.3.0 升级
- r - R ; How can I build 'for in' loops over datatable?
- python-3.x - 我正在运行基于人脸识别的代码有一个错误
- android - 使用 Android MVVM,如何避免在回收器适配器中再次设置相同的数据?
- python-3.x - 如何使用 Ec2 实例运行 Lambda 函数
- ios - Swift UITableView GoTo Other Row 当在 viewWillAppear 中访问 tableView.reloadData()