Python实现GitHub认证接口JSON转指定标签CSV代码请求
解答:用Python带Token请求GitHub API并导出指定数据到CSV
Hey there! As someone new to Python, let's walk through this step by step—this will be simple to follow with clear explanations and code you can tweak for your needs.
第一步:准备需要的工具
First, we'll use a couple of key tools:
requests: To send authenticated requests to GitHub's API (this isn't part of Python's standard library, so you'll need to install it first)csvandjson: These come built into Python, so no extra installation needed.
Install requests by running this in your terminal:
pip install requests
第二步:完整实现代码
Here's the code with comments explaining every part. I'll use an example of fetching tags from a GitHub repository (you can swap the API URL to fetch other data like issues, releases, etc.):
import requests import csv # ---------------------- 配置参数 ---------------------- # 替换成你的GitHub个人访问Token(在GitHub设置里生成) GITHUB_TOKEN = "your-personal-access-token-here" # 替换成你要请求的GitHub API接口地址,比如获取某个仓库的标签列表 API_URL = "https://api.github.com/repos/octocat/Hello-World/tags" # 替换成你想要提取的指定字段(根据API返回的JSON结构调整) TARGET_FIELDS = [ "tag_name", # 标签名称 "commit_sha", # 标签对应的commit哈希值 "download_url" # 标签压缩包的下载地址 ] # ---------------------- 发送认证请求 ---------------------- # 设置请求头,携带Token完成身份验证 headers = { "Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json" # 指定使用GitHub API的v3版本 } try: response = requests.get(API_URL, headers=headers) # 检查请求是否成功,失败则抛出异常 response.raise_for_status() except requests.exceptions.RequestException as e: print(f"请求出错啦: {e}") exit() # 将响应内容转换成JSON格式的数据 raw_data = response.json() # ---------------------- 过滤指定字段 ---------------------- # 处理嵌套字段(比如commit里的sha),整理成CSV需要的扁平结构 filtered_data = [] for item in raw_data: # 从原始数据中提取需要的字段,嵌套字段用.get()避免报错 row = { "tag_name": item.get("name"), "commit_sha": item.get("commit", {}).get("sha"), "download_url": item.get("zipball_url") } # 只保留我们预先指定的字段 cleaned_row = {key: row[key] for key in TARGET_FIELDS if key in row} filtered_data.append(cleaned_row) # ---------------------- 写入CSV文件 ---------------------- if filtered_data: with open("github_tags.csv", mode="w", newline="", encoding="utf-8") as csv_file: # 使用DictWriter自动处理表头和行数据 writer = csv.DictWriter(csv_file, fieldnames=TARGET_FIELDS) writer.writeheader() # 写入表头 writer.writerows(filtered_data) # 写入所有行数据 print("数据已成功保存到 github_tags.csv 文件中!") else: print("没有获取到可处理的数据哦。")
关键细节说明
- GitHub Token: 你需要在GitHub账户的「开发者设置」→「个人访问令牌」里生成一个Token,记得给它分配必要的权限(比如访问私有仓库需要
repo权限)。 - API URL: 你可以把这个地址换成任何GitHub API接口,比如要获取仓库的issues就用
https://api.github.com/repos/{owner}/{repo}/issues,根据你的需求调整即可。 - 字段调整: 如果API返回的JSON里有其他你需要的字段,只需要更新
TARGET_FIELDS列表,同时调整row字典里的提取逻辑就行(比如要提取作者用户名可以写item["author"]["login"])。 - 错误处理: 代码里的
try-except块会捕获网络错误、无效Token等常见问题,避免程序直接崩溃,还会给出清晰的错误提示。
内容的提问来源于stack exchange,提问作者RAMESHKUMAR
相关产品推荐
相关产品推荐

