forked from ping/newsrack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathatlantic-magazine.recipe.py
238 lines (203 loc) · 9.25 KB
/
atlantic-magazine.recipe.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
# Original at https://github.com/kovidgoyal/calibre/blob/ce8b82f8dc70e9edca4309abc523e08605254604/recipes/atlantic.recipe
from __future__ import unicode_literals
import json
import os
import re
import sys
# custom include to share code between recipes
sys.path.append(os.environ["recipes_includes"])
from recipes_shared import BasicNewsrackRecipe, get_datetime_format, parse_date
from calibre.ebooks.BeautifulSoup import BeautifulSoup
from calibre.web.feeds.news import BasicNewsRecipe
def embed_image(soup, block):
caption = block.get("captionText", "")
if caption and block.get("attributionText", "").strip():
caption += " (" + block["attributionText"].strip() + ")"
container = soup.new_tag("div", attrs={"class": "article-img"})
img = soup.new_tag("img", src=block["url"])
container.append(img)
cap = soup.new_tag("div", attrs={"class": "caption"})
cap.append(BeautifulSoup(caption))
container.append(cap)
return container
def json_to_html(data):
# open('/t/p.json', 'w').write(json.dumps(data, indent=2))
data = sorted(
(v["data"] for v in data["props"]["pageProps"]["urqlState"].values()), key=len
)[-1]
article = json.loads(data)["article"]
new_soup = BeautifulSoup(
"""<html><head></head><body><main id="from-json-by-calibre"></main></body></html>"""
)
if article.get("issue"):
issue_ele = new_soup.new_tag("div", attrs={"class": "issue"})
issue_ele.append(article["issue"]["issueName"])
new_soup.main.append(issue_ele)
headline = new_soup.new_tag("h1", attrs={"class": "headline"})
headline.append(BeautifulSoup(article["title"]))
new_soup.main.append(headline)
subheadline = new_soup.new_tag("h2", attrs={"class": "sub-headline"})
subheadline.append(BeautifulSoup(article["dek"]))
new_soup.main.append(subheadline)
meta = new_soup.new_tag("div", attrs={"class": "article-meta"})
authors = [x["displayName"] for x in article["authors"]]
author_ele = new_soup.new_tag("span", attrs={"class": "author"})
author_ele.append(", ".join(authors))
meta.append(author_ele)
# Example: 2022-04-04T10:00:00Z "%Y-%m-%dT%H:%M:%SZ"
published_date = parse_date(article["datePublished"])
pub_ele = new_soup.new_tag("span", attrs={"class": "published-dt"})
pub_ele["data-published"] = f"{published_date:%Y-%m-%dT%H:%M:%SZ}"
pub_ele.append(f"{published_date:{get_datetime_format()}}")
meta.append(pub_ele)
if article.get("dateModified"):
# "%Y-%m-%dT%H:%M:%SZ"
modified_date = parse_date(article["dateModified"])
upd_ele = new_soup.new_tag("span", attrs={"class": "modified-dt"})
upd_ele["data-modified"] = f"{modified_date:%Y-%m-%dT%H:%M:%SZ}"
upd_ele.append(f"Updated {modified_date:{get_datetime_format()}}")
meta.append(upd_ele)
new_soup.main.append(meta)
if article.get("leadArt") and "image" in article["leadArt"]:
new_soup.main.append(embed_image(new_soup, article["leadArt"]["image"]))
for item in article["content"]:
tn = item.get("__typename", "")
if tn.endswith("Image"):
new_soup.main.append(embed_image(new_soup, item))
continue
content_html = item.get("innerHtml")
if (
(not content_html)
or "</iframe>" in content_html
or "newsletters/sign-up" in content_html
):
continue
if tn == "ArticleHeading":
tag_name = "h2"
mobj = re.match(r"HED(?P<level>\d)", item.get("headingSubtype", ""))
if mobj:
tag_name = f'h{mobj.group("level")}'
header_ele = new_soup.new_tag(tag_name)
header_ele.append(BeautifulSoup(content_html))
new_soup.main.append(header_ele)
continue
if tn == "ArticlePullquote":
container_ele = new_soup.new_tag("blockquote")
container_ele.append(BeautifulSoup(content_html))
new_soup.main.append(container_ele)
continue
if tn == "ArticleRelatedContentLink":
container_ele = new_soup.new_tag("div", attrs={"class": "related-content"})
container_ele.append(BeautifulSoup(content_html))
new_soup.main.append(container_ele)
continue
content_ele = new_soup.new_tag(item.get("tagName", "p").lower())
content_ele.append(BeautifulSoup(content_html))
new_soup.main.append(content_ele)
return str(new_soup)
class NoJSON(ValueError):
pass
_name = "The Atlantic Magazine"
_issue_url = ""
class TheAtlanticMagazine(BasicNewsrackRecipe, BasicNewsRecipe):
title = _name
description = "Current affairs and politics focused on the US https://www.theatlantic.com/magazine/"
INDEX = "https://www.theatlantic.com/magazine/"
__author__ = "Kovid Goyal"
language = "en"
masthead_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/The_Atlantic_magazine_logo.svg/1200px-The_Atlantic_magazine_logo.svg.png"
publication_type = "magazine"
compress_news_images_auto_size = 12
remove_attributes = ["style"]
remove_tags = [dict(class_=["related-content"])]
extra_css = """
.issue { font-weight: bold; margin-bottom: 0.2rem; }
.headline { font-size: 1.8rem; margin-bottom: 0.4rem; }
.sub-headline { font-size: 1.2rem; font-style: italic; font-weight: normal; margin-bottom: 0.5rem; }
.article-meta { margin-top: 0.5rem; margin-bottom: 1rem; }
.article-meta .author { font-weight: bold; color: #444; display: inline-block; }
.article-meta .published-dt { display: inline-block; margin-left: 0.5rem; }
.article-meta .modified-dt { display: block; margin-top: 0.2rem; font-style: italic; }
.caption { font-size: 0.8rem; margin-top: 0.2rem; margin-bottom: 0.5rem; }
.article-img { display: block; max-width: 100%; height: auto; }
h3 span.smallcaps { font-weight: bold; }
p span.smallcaps { text-transform: uppercase; }
blockquote { font-size: 1.25rem; margin-left: 0; text-align: center; }
div.related-content { margin-left: 0.5rem; color: #444; font-style: italic; }
"""
def extract_html(self, soup):
data = self.get_script_json(
soup, "", attrs={"id": "__NEXT_DATA__", "src": False}
)
if not data:
raise NoJSON("No script tag with JSON data found")
return json_to_html(data)
def get_browser(self):
br = BasicNewsRecipe.get_browser(self)
br.set_cookie("inEuropeanUnion", "0", ".theatlantic.com")
return br
def preprocess_raw_html(self, raw_html, url):
try:
return self.extract_html(self.index_to_soup(raw_html))
except NoJSON:
self.log.warn("No JSON found in: {} falling back to HTML".format(url))
except Exception:
self.log.exception(
"Failed to extract JSON data from: {} falling back to HTML".format(url)
)
return raw_html
def preprocess_html(self, soup):
for img in soup.findAll("img", attrs={"data-srcset": True}):
data_srcset = img["data-srcset"]
if "," in data_srcset:
img["src"] = data_srcset.split(",")[0]
else:
img["src"] = data_srcset.split()[0]
for img in soup.findAll("img", attrs={"data-src": True}):
img["src"] = img["data-src"]
return soup
def populate_article_metadata(self, article, soup, _):
headline = soup.find("h1", attrs={"class": "headline"})
if headline:
# reset the title because the title in the rss feed can contain tags, e.g. <em>
article.title = headline.text
published = soup.find(attrs={"data-published": True})
if published:
# "%Y-%m-%dT%H:%M:%SZ"
published_date = self.parse_date(published["data-published"])
article.utctime = published_date
if (not self.pub_date) or published_date > self.pub_date:
self.pub_date = published_date
def parse_index(self):
soup = self.index_to_soup(_issue_url if _issue_url else self.INDEX)
data = self.get_script_json(
soup, "", attrs={"id": "__NEXT_DATA__", "src": False}
)
if not data:
raise NoJSON("No script tag with JSON data found")
issue = None
for t in (
data.get("props", {}).get("pageProps", {}).get("urqlState", {}).values()
):
d = json.loads(t["data"])
if not (
d.get("latestMagazineIssue")
or d.get("magazineIssue", {}).get("toc", {}).get("sections", [])
):
continue
issue = d.get("latestMagazineIssue") or d.get("magazineIssue")
self.title = f'{_name}: {issue["displayName"]}'
self.cover_url = (
issue["cover"]["srcSet"].split(",")[-1].strip().split(" ")[0].strip()
)
feeds = []
for section in issue["toc"]["sections"]:
articles = [
{"url": i["url"], "title": i["title"], "description": i["dek"]}
for i in section.get("items", [])
]
feeds.append((section["title"], articles))
return feeds