File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed
Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ import requests
2+ import json
3+
4+ #执行api调用并查看响应
5+ url = 'https://hacker-news.firebaseio.com/v0/item/31353677.json'
6+ r = requests .get (url )
7+ print (f"Status code: { r .status_code } " )
8+
9+ #探索数据结构
10+ response_dict = r .json ()
11+ response_str = json .dumps (response_dict , indent = 4 )
12+ print (response_str )
Original file line number Diff line number Diff line change 1+ from operator import itemgetter
2+
3+ import requests
4+
5+ #执行api调用并查看响应
6+ url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
7+ r = requests .get (url )
8+ print (f"Status code: { r .status_code } " )
9+
10+ #处理每篇文章的信息
11+ submission_ids = r .json ()
12+ submission_dicts = []
13+ for submission_id in submission_ids [:5 ]:
14+ #对于每一篇文章都执行api调用
15+ url = f'https://hacker-news.firebaseio.com/v0/items/{ submission_id } .json'
16+ r = requests .get (url )
17+ print (f"id: { submission_id } \t Status code: { r .status_code } " )
18+ response_dict = r .json ()
19+
20+ #对于每一篇文章都创建一个字典
21+ try :
22+ submission_dict = {
23+ 'title' : response_dict ['title' ],
24+ 'hn_link' : f"https://news.ycombinator.com/item?id={ submission_id } " ,
25+ 'comments' : response_dict ['descendants' ],
26+ }
27+ submission_dicts .append (submission_dict )
28+ except KeyError :
29+ continue
30+
31+ submission_dicts = sorted (submission_dicts , key = itemgetter ('comments' ), reverse = True )
32+
33+ for submission in submission_dicts :
34+ print (f"\n Title: { submission ['title' ]} " )
35+ print (f"\n Discussion link: { submission ['hn_link' ]} " )
36+ print (f"\n Comments: { submission ['comments' ]} " )
You can’t perform that action at this time.
0 commit comments