练习题:网络请求与数据解析

考点:

  • 使用 requests 库进行HTTP请求
  • JSON数据解析
  • 字典操作
  • 异常处理

题目描述: 编写一个Python函数 get_user_github_info,该函数接受一个GitHub用户名作为参数,并从GitHub API获取该用户的个人信息。个人信息应包括用户的名字、公司、博客链接和位置。函数应返回一个包含这些信息的字典。

GitHub API的用户信息端点是:https://api.github.com/users/{username}

例如,如果函数被调用为 get_user_github_info('octocat'),它应该返回以下信息:

{
    'name': 'The Octocat',
    'company': 'GitHub',
    'blog': 'https://github.blog',
    'location': 'San Francisco'
}

作答区:

# 请在此处编写你的代码

答案

import requests

def get_user_github_info(username):
    url = f'https://api.github.com/users/{username}'
    try:
        response = requests.get(url)
        response.raise_for_status()  # 检查请求是否成功
        user_data = response.json()
        return {
            'name': user_data.get('name'),
            'company': user_data.get('company'),
            'blog': user_data.get('blog'),
            'location': user_data.get('location')
        }
    except requests.exceptions.HTTPError as e:
        print(f'HTTP error occurred: {e}')
    except requests.exceptions.RequestException as e:
        print(f'Request error occurred: {e}')
    return {}

www.smqlrc.com
www.smyxrcw.com
www.smhcrcw.com
www.smtarcw.com
www.zzyxrcw.com

# 测试代码
user_info = get_user_github_info('octocat')
print(user_info)

在这个答案中,我们使用了 requests 库来发送HTTP请求,并解析返回的JSON数据。同时,我们添加了异常处理来捕获可能发生的错误。

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值