描述問題
想跟蹤一個github項目,如果該項目更新了,自動打開網頁.
拆解問題
- 監測github項目更新,更新的標誌是什麼
監測網頁數據變化在於對比變化
如何獲取網頁資源:
- 接口API -> json
- 爬蟲 xml
如果有API就儘量用API,不爬蟲.
- 如何打開網頁
import webbrowser
webbrowser.open(url)
github API使用
如何閱讀API文檔,如何使用
如何利用什麼庫處理網頁內容,提取出自己需要的字段.
使用requests庫下載網頁, 持續運行while
import requests
all_info = requests.get(api).json()
# requests.get(api),返回的是狀態響應碼(eg.200), 使用json()轉化數據格式爲字典
通過字段之間的對比,來判斷github項目是否更新了
如果更新了, 就打開網頁.
代碼
import requests
import webbrowser
import time
api_url = "https://api.github.com/repos/channelcat/sanic"
github_url = "https://github.com/channelcat/sanic"
# get_data -> diff_data -> open url
all_info = requests.get(api_url).json()
old_time = None
# old_time = "2016-06-08T12:30:07Z"
# 爲了測試程序,可以先給old_time賦值
while True:
new_time = all_info["updated_at"]
if not old_time:
old_time = all_info["updated_at"]
if new_time > old_time:
old_time = new_time
webbrowser.open(github_url)
time.sleep(100)