使用 Python 建立網站鬧鐘


在本節中,我們將瞭解如何使用 Python 建立網站警報系統。

問題陳述

透過獲取網站 URL 和時間,在瀏覽器中開啟網站 URL。當系統時間到達指定時間時,將開啟網頁。

我們可以在書籤部分儲存不同的網頁。有時我們需要每天在特定時間開啟一些網頁來完成一些工作。為此,我們可以設定這種型別的網站警報來完成工作。

在這種情況下,我們使用了一些標準庫模組,例如 sys、web browser 和 time。

在特定時間開啟網頁的步驟

  • 獲取將要開啟的 URL。
  • 獲取在該時間開啟網頁的時間。
  • 檢查當前時間是否與指定時間匹配。
    • 如果時間匹配,則開啟網頁。否則等待一秒鐘。
    • 每秒重複步驟 3,直到時間匹配。
  • 結束程序

示例程式碼

import time
import webbrowser
import sys
def web_alarm(url, alarm_time):
   current_time = time.strftime('%I:%M:%S')
   while(current_time != alarm_time):    #repeatedly check for current time and the alarm time
   print('Current time is: ' + current_time)
   current_time = time.strftime('%I:%M:%S')
   time.sleep(1)       #wait for one second
   if current_time == alarm_time:    #when the time matches, open the browser
      print('Opening the ' + url + ' now...')
      webbrowser.open(url)
web_alarm(sys.argv[1], sys.argv[2])    #Set the alarm using url and time

輸出

$ python3 397.Website_Alarm.py https://tutorialspoint.tw/ 02:01:00
Current time is: 02:00:46
Current time is: 02:00:46
Current time is: 02:00:47
Current time is: 02:00:48
Current time is: 02:00:49
Current time is: 02:00:50
Current time is: 02:00:51
Current time is: 02:00:52
Current time is: 02:00:53
Current time is: 02:00:54
Current time is: 02:00:55
Current time is: 02:00:56
Current time is: 02:00:57
Current time is: 02:00:58
Current time is: 02:00:59
Opening the https://tutorialspoint.tw/ now...
$

Website Alarm

更新於: 2019年7月30日

411 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告