Debian Codegraph @

recipes/business_standard_print.recipe

raw
1 #!/usr/bin/env python
2 # vim:fileencoding=utf-8
3 import json
4 from datetime import datetime
5
6 from html5_parser import parse
7
8 from calibre.web.feeds.news import BasicNewsRecipe
9
10
11 class BusinessStandardPrint(BasicNewsRecipe):
12 title = 'Business Standard Print Edition'
13 __author__ = 'unkn0wn'
14 description = "India's most respected business daily, Articles from Today's Paper"
15 language = 'en_IN'
16 masthead_url = 'https://bsmedia.business-standard.com/include/_mod/site/html5/images/business-standard-logo.png'
17 encoding = 'utf-8'
18
19 no_stylesheets = True
20 remove_javascript = True
21 remove_attributes = ['width', 'height', 'style']
22
23 def get_browser(self):
24 return BasicNewsRecipe.get_browser(self, user_agent='common_words/based')
25
26 ignore_duplicate_articles = {'title', 'url'}
27 remove_empty_feeds = True
28 resolve_internal_links = True
29 browser_type = 'webengine'
30
31 extra_css = '''
32 img {display:block; margin:0 auto;}
33 .sub { font-style:italic; color:#202020; }
34 .auth, .cat { font-size:small; color:#202020; }
35 .cap { font-size:small; text-align:center; }
36 '''
37
38 recipe_specific_options = {
39 'date': {
40 'short': 'The date of the print edition to download (DD-MM-YYYY format)',
41 'long': 'For example, 20-09-2023',
42 }
43 }
44
45 def get_cover_url(self):
46 d = self.recipe_specific_options.get('date')
47 if not (d and isinstance(d, str)):
48 soup = self.index_to_soup('https://www.magzter.com/IN/Business-Standard-Private-Ltd/Business-Standard/Newspaper/')
49 return soup.find('img', id=lambda s: s and 'mgd__lhd__cover' in s.split())['src']
50
51 def parse_index(self):
52 today = datetime.today().strftime('%d-%m-%Y')
53 d = self.recipe_specific_options.get('date')
54 if d and isinstance(d, str):
55 today = d
56
57 day, month, year = (int(x) for x in today.split('-'))
58 dt = datetime(year, month, day)
59 self.timefmt = ' [' + dt.strftime('%b %d, %Y') + ']'
60
61 if dt.weekday() == 6:
62 self.log.warn(
63 'Business Standard Does Not Have A Print Publication On Sunday. The Reports'
64 " And Columns On This Page Today Appeared In The Newspaper's Saturday Edition."
65 )
66 url = 'https://apibs.business-standard.com/category/today-paper?sortBy=' + today
67 raw = self.index_to_soup(url, raw=True)
68 data = json.loads(raw)
69 data = data['data']
70
71 feeds = []
72
73 for section in data:
74 if section == 'EpaperImage':
75 continue
76 self.log(section)
77 articles = []
78 for article in data[section]:
79 title = article['heading1']
80 desc = article['sub_heading']
81 url = 'https://www.business-standard.com' + article['article_url']
82 self.log('\t', title, '\n\t', desc, '\n\t\t', url)
83 articles.append({'title': title, 'description': desc, 'url': url})
84 if articles:
85 feeds.append((section, articles))
86 return feeds
87
88 def preprocess_raw_html(self, raw, *a):
89 root = parse(raw)
90 m = root.xpath('//script[@id="__NEXT_DATA__"]')
91
92 data = json.loads(m[0].text)
93
94 img_url = None
95 if 'articleImageUrl' in data['props']['pageProps']['articleSchema']:
96 img_url = data['props']['pageProps']['articleSchema']['articleImageUrl']
97
98 art_url = 'https://www.business-standard.com' + data['props']['pageProps']['url']
99
100 data = data['props']['pageProps']['data']
101
102 title = '<h1 title="{}">'.format(art_url) + data['pageTitle'] + '</h1>'
103
104 cat = subhead = lede = auth = caption = ''
105
106 if 'defaultArticleCat' in data and data['defaultArticleCat'] is not None:
107 if 'h1_tag' in data['defaultArticleCat'] and data['defaultArticleCat']['h1_tag'] is not None:
108 cat = '<div class="cat">' + data['defaultArticleCat']['h1_tag'] + '</div>'
109
110 if 'metaDescription' in data and data['metaDescription'] is not None:
111 subhead = '<p class="sub">' + data['metaDescription'] + '</p>'
112 self.art_desc = data['metaDescription']
113
114 date = (datetime.fromtimestamp(int(data['publishDate']))).strftime('%b %d, %Y | %I:%M %p')
115
116 authors = []
117 if 'articleMappedMultipleAuthors' in data:
118 for aut in data['articleMappedMultipleAuthors']:
119 authors.append(data['articleMappedMultipleAuthors'][str(aut)])
120 auth = '<div><p class="auth">' + ', '.join(authors) + ' | ' + data['placeName'] + ' | ' + date + '</p></div>'
121
122 if 'featuredImageObj' in data:
123 if 'url' in data['featuredImageObj']:
124 if img_url is not None:
125 lede = '<br><div class="cap"><img src="{}">'.format(img_url)
126 else:
127 lede = '<br><div class="cap"><img src="{}">'.format(data['featuredImageObj']['url'])
128 if 'alt_text' in data['featuredImageObj']:
129 caption = '<span>' + data['featuredImageObj']['alt_text'] + '</span></div>'
130
131 body = '<div id="bdy">' + data['htmlContent'] + '</div>'
132
133 return '<html><body>' + cat + title + subhead + auth + lede + caption + body + '</body></html>'
134
135 def preprocess_html(self, soup):
136 bdy = soup.find('div', attrs={'id': 'bdy'})
137 for p in bdy.findAll('div', attrs={}):
138 p.name = 'p'
139 for small in soup.findAll('small', attrs={'class': 'brtag'}):
140 small.decompose()
141 for img in soup.findAll('img'):
142 img.attrs = {'src': img.get('src', '')}
143 for x in soup.findAll('div', 'p'):
144 x.attrs = {'class': x.get('class', '')}
145 for attr in self.remove_attributes:
146 for x in soup.findAll(attrs={attr: True}):
147 del x[attr]
148 for br in soup.findAll(attrs={'class': lambda x: x and x.startswith('brtag')}):
149 br.name = 'div'
150 return soup