【发布时间】:2017-04-03 23:49:21
【问题描述】:
GitHub 上的用户资料显示用户在过去一年中所做的贡献数量:
我想在我的网站上显示这些信息,最好不要引入任何类型的后端。我在好几个地方都找过了。 /users/(me)/ 中未列出任何内容。没有抓取页面源,有没有办法检索这些信息?我没有看到任何记录...
【问题讨论】:
标签: javascript github client-side github-api
GitHub 上的用户资料显示用户在过去一年中所做的贡献数量:
我想在我的网站上显示这些信息,最好不要引入任何类型的后端。我在好几个地方都找过了。 /users/(me)/ 中未列出任何内容。没有抓取页面源,有没有办法检索这些信息?我没有看到任何记录...
【问题讨论】:
标签: javascript github client-side github-api
还可以使用 xml 解析器解析 svg 日历数据,然后对所有 data-count 条目求和。为避免 CORS 问题,您可以使用像 urlreq 这样的代理,生活在 http://urlreq.appspot.com/req 上:
const user = 'controversial';
fetch('https://urlreq.appspot.com/req?method=GET&url=https://github.com/users/' + user + '/contributions')
.then(function(response) {
return response.text();
})
.then(function(text) {
xmlDoc = new DOMParser().parseFromString(text, 'text/xml');
var nodes = xmlDoc.getElementsByTagName('rect');
var count = 0;
for (var i = 0; i < nodes.length; i++) {
count += parseInt(nodes[i].getAttribute('data-count'));
}
console.log('contributions count : ' + count);
})
.catch(function(error) {
console.log('Request failed', error)
});
另一个使用curl & xmlstarlet 的命令行示例可以找到here
【讨论】:
我已经决定使用 PHP 解析我的个人资料页面的 HTML。我首先下载我的个人资料页面的 HTML:
$githubProfile = file_get_contents('https://github.com/controversial');
接下来我在页面上找到短语contributions in the last year 的位置。 contributions 和 in the last year 之间的空格很奇怪,所以我使用正则表达式来匹配任意数量的空间。
$contributionsIndex = preg_match(
'/contributions\s+in the last year/',
$githubProfile,
$matches,
PREG_OFFSET_CAPTURE
);
$index = $matches[0][1];
最后,我从这一点向后迭代,直到遇到一个既不是数字也不是数字中的逗号的字符。一旦这个条件变为假,我就知道我找到了数字的开头:
$endIndex = $index;
while (is_numeric($githubProfile[$index-2]) || $githubProfile[$index-2] == ',')
$index--;
$contributionsCount = substr($githubProfile, $index-1, $endIndex-$index);
最后,我将数字呼出(不带逗号)
echo(str_replace(',', '', $contributionsCount));
最后,我使用 JavaScript 页面中的 AJAX 调用从 PHP 脚本中获取值。
function get(url, callback) {
/* eslint-disable no-console */
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = e => (callback || console.log)(e.target.responseText);
xhr.onerror = () => console.log('error');
xhr.send();
/* eslint-enable no-console */
}
// Fill in GitHub contributions count
get('contributions-count.php', (resp) => {
document.getElementById('gh-contributions-count').innerText = resp;
});
我相信这将在未来使用 GitHub 的 GraphQL API 更清晰地完成,但这仍处于预览阶段。
【讨论】:
你见过GithubAPI吗?使用它,您可以从您的 js 文件运行请求,而无需实现任何后端。
出于您的目的,我认为您可以使用以下请求https://api.github.com/users/yourUserName/events。这会为您提供与 youUserName 相关的事件列表。
例如
[
{
"id": "xxxxxxx",
"type": "PushEvent",
"actor": {.......},
"repo": {......},
"payload": {.......},
"public": true,
"created_at": "2016-11-17T21:33:15Z"
},
.....
]
您应该浏览列表并过滤 type = PushEvent 和 created_at = lastYear。
希望对你有帮助!
更新:该服务仅提供过去 3 个月的结果,因此其他可能性是检查 (users/username/repos),然后检查他们的提交 (repos/username/repoName/commits)
【讨论】: