Skip to content

Commit 56e0a24

Browse files
committed
another example complete
1 parent 1c2b665 commit 56e0a24

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

hn_article.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
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)

hn_submissions.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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}\tStatus 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"\nTitle: {submission['title']}")
35+
print(f"\nDiscussion link: {submission['hn_link']}")
36+
print(f"\nComments: {submission['comments']}")

0 commit comments

Comments
 (0)