| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
import json |
| 13 |
import sys |
| 14 |
import urllib.request |
| 15 |
import xml.etree.ElementTree as ET |
| 16 |
|
| 17 |
|
| 18 |
atom_ns = {"atom": "http://www.w3.org/2005/Atom"} |
| 19 |
article_parser_url = "https://extract-article.deta.dev/?url=" |
| 20 |
|
| 21 |
|
| 22 |
def process_article(article, is_rss, is_atom): |
| 23 |
try: |
| 24 |
|
| 25 |
scraped_article = "" |
| 26 |
|
| 27 |
if is_rss: |
| 28 |
article_link = article.find("link").text |
| 29 |
elif is_atom: |
| 30 |
article_link = article.find("atom:link", atom_ns).attrib['href'] |
| 31 |
|
| 32 |
|
| 33 |
link = article_parser_url + article_link |
| 34 |
|
| 35 |
response = urllib.request.urlopen(link) |
| 36 |
text = response.read().decode("utf-8") |
| 37 |
js = json.loads(text) |
| 38 |
|
| 39 |
if int(js["error"]) == 0: |
| 40 |
scraped_article = js["data"]["content"] |
| 41 |
|
| 42 |
|
| 43 |
if scraped_article: |
| 44 |
if is_rss: |
| 45 |
article.find("description").text = scraped_article |
| 46 |
elif is_atom: |
| 47 |
at_con = article.find("atom:content", atom_ns) |
| 48 |
|
| 49 |
if at_con is None: |
| 50 |
article.find("atom:summary", atom_ns).text = scraped_article |
| 51 |
else: |
| 52 |
at_con.text = scraped_article |
| 53 |
except Exception as e: |
| 54 |
pass |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
def main(): |
| 59 |
no_threads = int(sys.argv[1]) if len(sys.argv) >= 2 else 1 |
| 60 |
|
| 61 |
if no_threads > 1: |
| 62 |
import asyncio |
| 63 |
from concurrent.futures import ThreadPoolExecutor |
| 64 |
|
| 65 |
sys.stdin.reconfigure(encoding="utf-8") |
| 66 |
|
| 67 |
|
| 68 |
feed_data = sys.stdin.read() |
| 69 |
feed_document = ET.fromstring(feed_data) |
| 70 |
|
| 71 |
|
| 72 |
is_rss = feed_document.tag == "rss" |
| 73 |
is_atom = feed_document.tag == "{http://www.w3.org/2005/Atom}feed" |
| 74 |
|
| 75 |
if not is_rss and not is_atom: |
| 76 |
sys.exit("Passed file is neither ATOM nor RSS 2.0 feed.") |
| 77 |
|
| 78 |
|
| 79 |
if is_rss: |
| 80 |
feed_articles = feed_document.findall(".//item") |
| 81 |
elif is_atom: |
| 82 |
feed_articles = feed_document.findall(".//atom:entry", atom_ns) |
| 83 |
|
| 84 |
|
| 85 |
if no_threads > 1: |
| 86 |
with ThreadPoolExecutor(max_workers=no_threads) as executor: |
| 87 |
futures = [] |
| 88 |
for article in feed_articles: |
| 89 |
futures.append( |
| 90 |
executor.submit(process_article, article, is_rss, is_atom)) |
| 91 |
for future in futures: |
| 92 |
future.result() |
| 93 |
else: |
| 94 |
for article in feed_articles: |
| 95 |
process_article(article, is_rss, is_atom) |
| 96 |
|
| 97 |
print(ET.tostring(feed_document).decode()) |
| 98 |
|
| 99 |
|
| 100 |
if __name__ == '__main__': |
| 101 |
main() |