爬取Github Web API 并存入Mysql数据库

写在前面
本文内容为爬取GitHub的Web API并存入mysql数据库,内容为华为鸿蒙OS相关的代码。

WEB API
Web API是网络应用程序接口。它包含了广泛的功能,网络应用通过API接口,可以实现存储服务、消息服务、计算服务等能力。Web API最主要的功能是实现构建基于GTTP的面向各种客户端的服务框架。

Github 的 Web API
可以通过 https://api.github.com 查看Github 的 Web API列表
在这里插入图片描述
例如:https://api.github.com/repos/{owner}/{repo},可以通过用户名和仓库名获取到指定项目的有关内容。

(1)导入所需Python库

import requests
import pymysql

(2)定义指定的Web API的URL,并将其赋给变量api_url。

这里先设为 https://api.github.com/repos/Awesome-HarmonyOS/HarmonyOS
其中,Awesome-HarmonyOS表示用户名,HarmonyOS表示仓库名。

查看状态码,200为正常响应。

api_url= 'https://api.github.com/repos/Awesome-HarmonyOS/HarmonyOS'
req = requests.get(api_url)
print('状态码:', req.status_code)

可以直接在浏览器中进行访问,查看数据大致情况如下图所示:

在这里插入图片描述
可以看到,响应数据包含的值较多,因此在爬取之后可以考虑对数据进行简单清洗,只保留一些需要的重要信息。

(3)使用requests库的get方法获得Web API的Response对象。

req = requests.get(api_url)

(4)使用json方法将Response的数据转换为JSON的数据对象。

req_dic = req.json()

(5)打印一些基本信息
在这里插入图片描述
在这里插入图片描述

上述做法可以成功爬取到指定HarmonyOS仓库的信息,接下来爬取所有与HarmonyOS有关的仓库信息。

(6)将api_url改为https://api.github.com/search/repositories?q=HarmonyOS

搜索关键词为HarmonyOS的仓库

api_url= 'https://api.github.com/search/repositories?q=HarmonyOS'
req = requests.get(api_url)
print('状态码:', req.status_code)
req_dic = req.json()

(7)查看本次Web API请求是否完成,false表示完成。以及返回项目数量。

req_dic_items = req_dic['items']
print(req_dic['incomplete_results'])
print(len(req_dic_items))

(8)使用pymysql连接数据库,创建数据库、表并插入数据。
通过pymysql库的connect方法返回数据库连接对象db,在改方法中传入参数host、user、password等。

# 创建数据库
db = pymysql.connect(host='localhost', user='root', password='', port=3306)
cursor = db.cursor()
cursor.execute('CREATE DATABASE WebAPI DEFAULT CHARACTER SET utf8mb4')
print("create database successfully")

# 创建表
db2 = pymysql.connect(host='localhost', user='root', password='', database='WebAPI', port=3306)
cursor2 = db2.cursor()
# cursor2.execute('DROP TABLE IF EXISTS HarmonyOS')
sql1 = """CREATE TABLE `HarmonyOS`(
          `id` int(10) NOT NULL AUTO_INCREMENT,
          `name` char(50) NOT NULL,
          `owner_login` char(20) NOT NULL,
          `description` text DEFAULT NULL,
          `stargazers_count` int(10) NOT NULL,
          PRIMARY KEY(`id`)
          )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"""

try:
    cursor2.execute(sql1)
    db2.commit()
    print("created table successfully")
except:
    db2.rollback()
    print("created table failed")

# 插入数据
for index,key in enumerate(req_dic_items):
    sql2 = 'INSERT INTO HarmonyOS' \
           '(name, owner_login, description, stargazers_count)' \
           'VALUES (%s, %s, %s, %s)'
    try:
        cursor2.execute(sql2, (key['name'], key['owner']['login'], key['description'], key['stargazers_count']))
        db2.commit()
    except:
        db2.rollback()
        print("Insert failed")
db2.close()

最终结果
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值