如何使用 Python 檢查網站載入時間


我們在日常生活中使用不同的網站。每個特定的網站都需要一些時間來載入內容。從數學上講,我們可以透過將獲得的時間減去整個網站的讀取時間來獲得載入時間。在 Python 中,我們有一些包和模組來檢查網站的載入時間。

步驟/方法

以下是我們獲取網站載入時間需要遵循的步驟。讓我們一步一步地瞭解每個步驟。

  • 首先,我們必須將所需的庫匯入到我們的 Python 環境中。以下是程式碼行。

import requests
import time

requests 模組用於獲取網站的 URL,time 模組用於獲取網站載入內容所花費的時間。

  • 現在,我們將透過 time 模組的 time() 函式獲取網站載入的開始時間。

start_time = time.time()
  • 接下來,我們必須將我們想要檢查載入時間的 URL 傳遞到 requests 模組的 get() 函式。

response = requests.get("https://tutorialspoint.tw")
  • 現在,我們將再次透過 time 模組的 time() 函式獲取網站載入的結束時間。

end_time = time.time()
  • 在此步驟中,我們將透過減去開始時間和結束時間來計算網站的載入時間。

loading_time = end_time - start_time

示例

讓我們將上述程式碼步驟組合起來,獲取定義的網站載入內容所需的時間。

import requests
import time
url = "https://tutorialspoint.tw"  
start_time = time.time()
response = requests.get(url)
end_time = time.time()
loading_time = end_time - start_time
print(f"The loading time for the website {url} is {loading_time} seconds.")

輸出

以下是網站載入內容所需時間的輸出。

The loading time for the website https://tutorialspoint.tw is 0.48038482666015625 seconds.

示例

這是一個獲取網站載入內容所需時間的另一個示例。

def load_time(url):
    import requests
    import time 
    start_time = time.time()
    response = requests.get(url)
    end_time = time.time()
    loading_time = end_time - start_time
    print(f"The loading time for the website {url} is {loading_time} seconds.")
load_time("https://www.google.com")

輸出

以下是網站載入時間的輸出。

The loading time for the website https://www.google.com is 0.3369772434234619 seconds.

更新於: 2023年8月9日

611 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告