python学习——使用webAPI

发布时间:2019-08-09 10:19:56编辑:auto阅读(1891)

    1、Web API

    是网站的一部分,用于与使用非常具体的URL请求特定信息的程序交互。这种请求称为API调用。请求的数据将以易于处理的格式(JSON或CSV)返回。

    2、GitHub

    GitHub是一个让程序员能够协作开发项目的网站。GitHub上的项目都存储在仓库中,后者包含与项目相关联的一切:代码、项目参与者的信息、问题或bug报告等。

    3、使用pip安装requests

    requests包能让python程序轻松的向网站请求信息以及检查返回的相应。
    安装命令如下:
    这里写图片描述

    4、处理API响应

    #python_repos.py
    #coding=gbk
    import requests
    
    #执行API调用并存储响应
    url='https://api.github.com/search/repositories?q=language:python&sort=stars'
    
    #获得响应对象
    r=requests.get(url)
    
    #获得状态码
    print("status code:",r.status_code)
    
    #将API响应存储在一个变量中,这个API返回JSON格式的信息,使用方法json把这些信息转换为一个python字典
    response_dict=r.json()
    print("Total repositories:",response_dict['total_count'])

    这里写图片描述

    5、处理响应字典

    #探索有关仓库的信息
    repo_dicts=response_dict['items']
    print("Repositories returned:",len(repo_dicts))
    
    print("\nSelected information about each repository:")
    for repo_dict in repo_dicts:
        print('\nName:',repo_dict['name'])
        print('Owner:',repo_dict['owner']['login'])
        print('Stars:',repo_dict['stargazers_count'])
        print('Repository:',repo_dict['html_url'])
        print('Description:',repo_dict['description'])
    

    这里写图片描述

    6、使用pygal可视化仓库

    #探索有关仓库的信息
    repo_dicts=response_dict['items']
    
    names,stars=[],[]
    for repo_dict in repo_dicts:
        names.append(repo_dict['name'])
        stars.append(repo_dict['stargazers_count'])
    
    #可视化
    my_style=LS('#333366',base_style=LCS)
    
    #创建pygal类的config实例,通过修改其属性,可定制图表外观
    my_config=pygal.Config()
    
    #让标签绕x轴旋转45度
    my_config.x_label_rotation=45
    #隐藏了图例
    my_config.show_legend=False
    
    #设置图表标题、副标签和主标签的字体大小
    my_config.title_font_size=24
    my_config.label_font_size=14
    my_config.major_label_font_size=18
    
    #将较长的项目名缩短为15个字符
    my_config.truncate_label=15
    
    #隐藏图表中的水平线,设置自定义宽度
    my_config.show_y_guides=False
    my_config.width=1000
    
    chart=pygal.Bar(my_config,style=my_style)
    chart.title='Most-starred Python Projects on GitHub'
    chart.x_labels=names
    
    chart.add('',stars)
    chart.render_to_file('python_repos.svg')
    
    

    这里写图片描述

    7、添加自定义工具提示和可点击的链接

    for repo_dict in repo_dicts:
        names.append(repo_dict['name'])
        plot_dict={
            'value':repo_dict['stargazers_count'],
            'label':repo_dict['description'],
            'xlink':repo_dict['html_url']
            }
        plot_dicts.append(plot_dict)
    chart.add('',plot_dicts)

    这里写图片描述

关键字