File size: 1,403 Bytes
fbf3c28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""
id: rss
title: RSS/Atom Ingest
author: admin
description: Fetch and parse RSS/Atom feeds; return items with title/link.
version: 0.1.0
license: Proprietary
"""

import urllib.request
import xml.etree.ElementTree as ET


class Tools:
    def fetch(self, feed_url: str, max_items: int = 20) -> dict:
        xml = urllib.request.urlopen(feed_url, timeout=20).read()
        root = ET.fromstring(xml)
        items = []
        # RSS
        for it in root.findall(".//item"):
            t = it.find("title").text if it.find("title") is not None else ""
            link_url = it.find("link").text if it.find("link") is not None else ""
            items.append({"title": t or "", "link": link_url or ""})
            if len(items) >= max_items:
                break
        # Atom
        if not items:
            ns = "{http://www.w3.org/2005/Atom}"
            for e in root.findall(".//" + ns + "entry"):
                t = (
                    e.find(ns + "title").text
                    if e.find(ns + "title") is not None
                    else ""
                )
                link_el = e.find(ns + "link")
                link_url = link_el.get("href") if link_el is not None else ""
                items.append({"title": t or "", "link": link_url or ""})
                if len(items) >= max_items:
                    break
        return {"count": len(items), "items": items}