pythonでwordpressのrssを使って最新の記事を取得してみたいけどできるか不安です

プログラミング

wordpressにrssが設定されてたので試しに使ってみました

rssとは?

RSS(Rich Site Summary)は新しい記事の情報を配信する仕組みです

FeedlyなどのRSSリーダーを使うことで、

RSSを配信しているブログなどの最新記事をすぐに見ることができます

wordpressのrssのURLは?

https://サイト名/feedです

このブログの場合は

https://otobou.com/feed/

です

pythonでrssを取得するには?

requestsでrssを取得します

    response = requests.get(url)
    text = response.text

ElementTreeでrssのxmlデータを解析します

    root = etree.fromstring(text)

find(“item”)で最新の記事を取得します

        root[0].find("item").find("title").text,
        root[0].find("item").find("link").text,
        root[0].find("item").find("description").text,
        root[0].find("item").find("{http://purl.org/rss/1.0/modules/content/}encoded").text

取得した結果をBlogクラスに詰め込みます

Blog(
        root[0].find("item").find("title").text,
        root[0].find("item").find("link").text,
        root[0].find("item").find("description").text,
        root[0].find("item").find("{http://purl.org/rss/1.0/modules/content/}encoded").text
    )

取得結果を表示します

    def show(self):
        print("タイトル:" + blog.title)
        print("URL:" + blog.url)

コード

ソースコード全体です

blog.py

import requests
import xml.etree.ElementTree as etree

class Blog:
    def __init__(self, title: str, url: str, description: str, content: str):
        self.title = title
        self.url = url
        self.description = description
        self.content = content

    def show(self):
        print("タイトル:" + blog.title)
        print("URL:" + blog.url)


def getBlog(url) -> Blog:
    response = requests.get(url)
    text = response.text
    root = etree.fromstring(text)
    return Blog(
        root[0].find("item").find("title").text,
        root[0].find("item").find("link").text,
        root[0].find("item").find("description").text,
        root[0].find("item").find("{http://purl.org/rss/1.0/modules/content/}encoded").text
    )


blog: Blog = getBlog("https://otobou.com/feed/")
blog.show()

実行結果

 % python3 blog.py
タイトル:体調悪いから好きなもの食べたらリバウンドして不安です
URL:https://otobou.com/2021/07/11/diet-2/

無事rssから最新の記事を取得できました

あとがき

作りたいものができたのでその足がかりのために調べました

pythonは癖があるので苦手です

コメント

タイトルとURLをコピーしました