
免费python编程教程:https://pan.quark.cn/s/2c17aed36b72
在开源技术蓬勃发展的今天,GitHub已成为全球开发者协作的核心平台。通过分析GitHub上的项目数据,开发者可以洞察技术趋势、发现热门工具,甚至挖掘潜在的合作机会。本文将结合实战案例,详细介绍如何用Python爬取GitHub开源项目信息,并通过词云技术直观展示技术关键词分布。

pip install requests PyGithub beautifulsoup4 lxml pandas jieba wordcloud matplotlib
GitHub提供REST API和GraphQL API,推荐使用PyGithub库简化操作:
from github import Github
# 使用Token认证(需在GitHub设置生成)
g = Github("your_github_token")
# 获取热门Python仓库
repos = g.search_repositories(query="language:python", sort="stars", order="desc")
for repo in repos[:10]: # 取前10个
print(f"{repo.name} - Stars: {repo.stargazers_count}")
优势:
当需要获取API未暴露的数据时,可通过解析HTML实现:
import requests
from bs4 import BeautifulSoup
headers = {
"User-Agent": "Mozilla/5.0",
"Accept-Language": "zh-CN"
}
url = "https://github.com/trending/python"
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "lxml")
for repo in soup.select(".Box-row"):
name = repo.select_one("h1 a").text.strip()
desc = repo.select_one(".f6").text.strip()
print(f"{name}\n{desc}\n")
注意事项:
使用pandas将爬取数据转为DataFrame:
import pandas as pd
data = {
"repo_name": ["tensorflow", "pytorch"],
"stars": [165000, 68000],
"description": ["机器学习框架", "深度学习框架"]
}
df = pd.DataFrame(data)
df.to_csv("github_repos.csv", index=False, encoding="utf-8")


from wordcloud import WordCloud
import matplotlib.pyplot as plt
text = " ".join(filtered_words)
wc = WordCloud(
font_path="simhei.ttf", # 中文字体路径
width=800,
height=600,
background_color="white",
max_words=100
).generate(text)
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.savefig("github_wordcloud.png", dpi=300)
plt.show()


def get_trending_repos(language="python", days="weekly"):
url = f"https://github.com/trending/{language}?since={days}"
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "lxml")
repos = []
for item in soup.select(".Box-row"):
name = item.select_one("h1 a").text.strip()
desc = item.select(".f6").text.strip().replace("\n", " ")
stars = item.select_one("a[href*='stargazers']").text.strip()
repos.append({"name": name, "desc": desc, "stars": stars})
return repos
# 合并所有描述文本
all_text = " ".join([repo["desc"] for repo in get_trending_repos()])
# 生成词云
wc = WordCloud(
font_path="msyh.ttc",
width=1000,
height=800,
max_words=150,
collocations=False # 避免重复词组
).generate(all_text)
plt.figure(figsize=(15, 10))
plt.imshow(wc)
plt.axis("off")
plt.tight_layout()
plt.savefig("trending_tech_wordcloud.png", bbox_inches="tight")
Q1:被网站封IP怎么办? A:立即启用备用代理池,建议:
requests.Session()实现自动轮换time.sleep(random.uniform(1, 3)))Q2:如何处理GitHub的反爬机制? A:
Cookie模拟真实用户(需定期更新)robots.txt规则Q3:词云中无关词汇过多如何解决? A:
min_word_length=2)Q4:PyGithub报错404怎么办? A:
repo权限)/repos/{owner}/{repo})
通过本文介绍的方法,开发者可以快速构建GitHub数据采集与分析系统。实际应用中可进一步扩展:
技术演进方向:
掌握GitHub数据爬取与可视化技术,不仅能提升个人技术洞察力,更为开源社区研究、技术选型等场景提供有力支持。建议从简单案例入手,逐步优化各环节性能,最终构建完整的数据处理流水线。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。