[TOC]
监控Github项目更新并自动打开网页
# -*- coding:utf-8 -*-
"""
@author: XueHaozhe
@file:检测github并自动打开网页.py
@time:2018/11/30 16:21
"""
# api https://api.github.com/repos/channelcat/sanic
# web_page https://github.com/channelcat/sanic
import requests
import webbrowser
import time
api = 'https://api.github.com/repos/channelcat/sanic'
web_page = 'https://github.com/channelcat/sanic'
last_update = '"2018-10-30T08:11:59Z"'
dict_info = requests.get(api).json()
cur_update = dict_info['updated_at']
while True:
if not last_update:
last_update = cur_update
if last_update < cur_update:
webbrowser.open(web_page)
time.sleep(600)
Kenneth Reitz 是 Python 领域的大神级人物,并且在 Github 上非常活跃,他的 Github 地址是:https://github.com/kennethreitz 试着用所学知识去发现 Kenneth 今天 Starred 了哪些库,并且自动在浏览器中打开这些库的地址。
问题拆解提示:
· 本问题可以拆解为以下若干子问题:
· 1.如何获取指定用户所star的项目?
· 2.如何判断新的项目出现?
· 3.如何打开网页?
· 4.如何保持程序每隔一段时间进行监测?
问题解决提示:
· 1.通过GitHub提供的api,获取指定用户所star的所有项目,并转换为json数据。然后,将其中的id字段都提取出来,存入list变量。该变量即为用户已经star的项目的列表。api的调用格式为:https://api.github.com/users/kennethreitz/starred,其中kennethreitz是用户名,是可变参数。
· 2.重复1中的步骤,然后对比list变量和刚刚抓取的数据,如果项目id不在list变量中,说明该项目是新出现的。
· 3.利用webbrowser模块,其中的open函数可以控制浏览器打开一个指定的页面。
· 4.while True语句是一个死循环,即为一个可以无限循环下去的语句,该语句可以控制程序一直运行。time模块中的sleep函数,可以让程序休眠一段时间,从而达到了每隔一段时间再运行的效果。
# -*- coding:utf-8 -*-
"""
@author: XueHaozhe
@file:Kenneth 今天 Star 了哪些库.py
@time:2018/11/30 17:22
"""
import requests
import webbrowser
import time
api = "https://api.github.com/users/kennethreitz/starred"
data = requests.get(api).json() #[{}]
starred = []
for i in data:
starred.append(i['id'])
while True:
info = requests.get(api).json()
for i in info:
# 如果当前项目id在list变量中不存在,则说明是刚刚star的项目
if not i['id'] in starred:
starred.append(i['id'])
repo_name = i['name']
owner = i['owner']['login']
# 在浏览器中打开项目
web_page = "https://github.com/" + owner + "/" + repo_name
webbrowser.open(web_page)
time.sleep(600) #十分钟
网友评论