ゆーじぇいブログ

ゆーじぇいブログ

プログラミングとか色々

[Django]NewsAPIを使って色々なニュースを取り出してみよう

f:id:jyouj:20181126215355p:plain

前回の記事の続きです!こちらでNewsAPIの導入が書かれています。

jyouj.hatenablog.com

今回は最新のニュースだけでなく、色々なニュースを絞り込んで取り出す、ということをやっていきましょう。

Djangoで作られています。

絞り込もう

例として、乃木坂46のニュースを取り出してみましょう。

class IndexView(generic.TemplateView):
    template_name = "news/index.html"

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        newsapi = NewsApiClient(api_key=settings.NEWSAPI)
        context['top_headlines'] = newsapi.get_everything(q='乃木坂46', from_param='2018-11-26',) #追加
        # print(context['top_headlines'])
        return context

get__everything()をつかってニュースを全て取り出します。ただ膨大なデータになるといけないのでfrom_paramsで取り出すニュースに制限を加えています。qに値を入れるだけで簡単に入手できます。

f:id:jyouj:20181127213342p:plain

アメリカのニュースを取り出そう

日本のニュースだけでなく、アメリカのニュースも取り出してみましょう!

class IndexView(generic.TemplateView):
    template_name = "news/index.html"

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        newsapi = NewsApiClient(api_key=settings.NEWSAPI)
        context['top_headlines'] = newsapi.get_top_headlines(country='us',) #変更
        # print(context['top_headlines'])
        return context

countryをusに変更するだけですね。他にもイギリスやカナダのニュースも取り出せるので、遊んでみましょう。

https://newsapi.org/docs/endpoints/top-headlines

f:id:jyouj:20181127213801p:plain

カテゴリーを絞ってみよう

テクノロジーに関するニュースだけみたい時ってありますよね?ということでカテゴリーごとに絞り込んでみましょう。

class IndexView(generic.TemplateView):
    template_name = "news/index.html"

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        newsapi = NewsApiClient(api_key=settings.NEWSAPI)
        context['top_headlines'] = newsapi.get_top_headlines(country='jp', category='technology') #変更
        # print(context['top_headlines'])
        return context

categoryを追加するだけですね!簡単!

f:id:jyouj:20181127214256p:plain

NewsAPI結構楽しいので、良ければ使ってみてください!

何かあれば、じぇい👨‍💻 (@jyouj__) | Twitterに!