Skip to content
This repository has been archived by the owner on Jun 6, 2023. It is now read-only.

実践編第6章 Hacker NewsのAPI hn_submissions.py のエラー #6

Open
zenich opened this issue Sep 1, 2020 · 0 comments
Open
Labels
documentation Improvements or additions to documentation

Comments

@zenich
Copy link
Collaborator

zenich commented Sep 1, 2020

問題の概要

実践編/chapter06/3_Hacker NewsのAPI/hn_submissions.py

の実行時に以下のようなエラーが出ることがあります。

Traceback (most recent call last):
  File "/saitan-python/実践編/chapter06/3_Hacker NewsのAPI/hn_submissions.py", line 24, in <module>
    'comments': response_dict['descendants'],
KeyError: 'descendants'

このエラーは取得した投稿のjsonに descendants というキーが含まれていない場合に発生します。
コードにはこのようなエラーに対応する処理が含まれていないので、プログラムは停止します。

なお同様の問題は saitan-python/やってみよう_実践編/chapter06/6_2_active_discussions.py でも起きる可能性があります。

簡易的な対処法

簡易的な対処法として、エラーが起きる直前のところで投稿の取得をやめてしまえば、プログラムは正常終了します。以下の行で投稿を取得する数を設定しています。

for submission_id in submission_ids[:30]:

ここで[:30]となっている数を、エラーが起きる投稿のひとつ前の数まで減らせば、とりあえず動くようになります。(1番目に descendants を含まない投稿があるとお手上げですが、、)

参考

エラーが起きる直前の出力を見ると、以下のように対象の投稿のidがわかります。

id: 24347836    status: 200

url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json"

を参考にidを埋め込むと対象の投稿のAPI呼び出しのURLがわかります。上記の場合は https://hacker-news.firebaseio.com/v0/item/24347836.json となります。
ブラウザで上記のURLを見てみると、jsonに descendants というキーが含まれていないことがわかります。

@zenich zenich added the documentation Improvements or additions to documentation label Sep 1, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant