Git เป็นระบบควบคุมเวอร์ชันยอดนิยมที่นักพัฒนาล้านๆ คนใช้จัดการโปรเจกต์และโค้ด ในบทความนี้เราจะดึงข้อมูล Top 10 repositories ที่ได้ดาว (star) มากที่สุดในแต่ละเดือนจาก GitHub Trending
ไลบรารีที่ใช้
- Requests: ดึงข้อมูลเว็บ
- BeautifulSoup: แยกวิเคราะห์ HTML (web scraping)
$ pip install requests beautifulsoup4 lxml
โค้ดตัวอย่าง
import requests
from bs4 import BeautifulSoup
# ดึงหน้า GitHub Trending สำหรับภาษา Lua รายเดือน
r = requests.get('https://github.com/trending/lua?since=monthly')
bs = BeautifulSoup(r.text, 'lxml')
# หารายการ repositories
lista_repo = bs.find_all('ol', class_='repo-list')
# บันทึกข้อมูลดิบลงไฟล์
with open('starred-repos.txt', 'w') as f1:
for lr in lista_repo:
aux = lr.find_all('div', class_='d-inline-block col-9 mb-1')
for ld in aux:
rank = ld.find_all('a')
f1.writelines(str(rank))
f1.writelines('\n')
# อ่านและแปลงข้อมูล
with open('starred-repos.txt', 'r') as f1:
texto = []
for x in f1:
if x[0] == '[' and x[1] == '<' and x[2] == 'a':
na = x.split('"')
texto.append(na[1])
# เขียนผลลัพธ์สุดท้าย
with open('starred-repos.txt', 'w') as f1:
f1.writelines('{}\t {}\t\t {}\t\n\n'.format('Position', 'Name', 'Repositories'))
for i in range(10):
tex = texto[i].split('/')
name = tex[1]
repos = tex[2]
f1.writelines('{}- \t {}\t\t {}\n'.format(i + 1, name, repos))
# แสดงผล
with open('starred-repos.txt', 'r') as f1:
print(f1.read())
ผลลัพธ์ตัวอย่าง
Position Name Repositories
1- skywind3000 z.lua
2- Kong kong
3- Gawen WireHub
4- PapyElGringo material-awesome
5- koreader koreader
6- stijnwop guidanceSteering
7- Courseplay courseplay
8- Tencent LuaPanda
9- ntop ntopng
10- awesomeWM awesome
หมายเหตุ
- โค้ดนี้ scraping จาก GitHub Trending ซึ่งโครงสร้าง HTML อาจเปลี่ยนแปลงได้ ต้องอัปเดต selector ตามไปด้วย
- ควรใช้ GitHub API อย่างเป็นทางการสำหรับการใช้งานจริง เพื่อความเสถียรและไม่ละเมิด Terms of Service
- สามารถปรับเปลี่ยนภาษา (lua) และช่วงเวลา (since=monthly) ได้ตามต้องการ