Python的网络编程

本文教你使用Python进行网络编程。

API请求

安装requests包

1
pip install --user requests

处理API响应

我们以找出GitHubStars最高的项目为例。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import requests
import matplotlib.pyplot as plt

url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
response_dict = r.json() #解析成字典

print('complete_results:', not response_dict['incomplete_results']) #获取的结果是否完整
print('total_count:', response_dict['total_count']) #GitHub上的Python项目总数
repo_len = len(response_dict['items']) #我们获取到的项目数量
print('get_repo_num:', repo_len)

forks = [0 for i in range(repo_len)]
stars = [0 for i in range(repo_len)]
for i in range(repo_len):
item = response_dict['items'][i]
print('rank:', i + 1)
print('name:', item['name'])
forks[i] = item['forks_count']
stars[i] = item['stargazers_count']
print('fork:', forks[i])
print('star:', stars[i])
print('--------------')

plt.plot([i for i in range(repo_len)], forks)
plt.plot([i for i in range(repo_len)], stars)
plt.legend(loc='upper right', labels=['forks', 'stars'])
plt.show()

输出结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
complete_results: True
total_count: 3660823
get_repo_num: 30
rank: 1
name: awesome-python
fork: 12560
star: 65258
--------------
rank: 2
...略...
star: 20375
--------------
rank: 30
name: python-patterns
fork: 4350
star: 19983
--------------

赏点钱吧(≧∇≦)ノ