Debian Codegraph @

recipes/alternatives_economiques.recipe

raw
1 #!/usr/bin/env python
2 import re
3
4 from calibre.web.feeds.news import BasicNewsRecipe
5
6
7 class AlternativesEconomiques(BasicNewsRecipe):
8 title = 'Alternatives Économiques'
9 __author__ = 'Kabonix'
10 description = 'Articles de toutes les rubriques (10 articles max par rubrique)'
11 publisher = 'Alternatives Économiques'
12 language = 'fr'
13
14 oldest_article = 90
15 max_articles_per_feed = 10
16 no_stylesheets = True
17 remove_javascript = True
18 encoding = 'utf-8'
19 auto_cleanup = False
20 remove_empty_feeds = True
21 remove_images = False
22
23 def get_cover_url(self):
24 """Récupère dynamiquement l'URL de la dernière une depuis MLP"""
25 br = self.get_browser()
26 try:
27 # Accéder à la page du magazine sur MLP
28 soup = self.index_to_soup(br.open('https://catalogueproduits.mlp.fr/produit.aspx?tit_code=1BMwusijpg0%3D').read())
29
30 # Chercher la div qui contient les images
31 gallery = soup.find('div', id='gallery')
32 if gallery:
33 img = gallery.find('img', id='couverture_1')
34 if img and img.get('src'):
35 cover_url = img['src']
36 if not cover_url.startswith('http'):
37 cover_url = 'https://catalogueproduits.mlp.fr/' + cover_url
38 self.log('Cover URL found:', cover_url)
39 return cover_url
40
41 self.log("Aucune couverture trouvée, utilisation de l'image par défaut")
42 return 'https://www.alternatives-economiques.fr/sites/all/themes/alternatives-economiques-main/assets/logo-alternatives-economiques.svg'
43
44 except Exception as e:
45 self.log.error('Erreur lors de la récupération de la couverture:', str(e))
46 return 'https://www.alternatives-economiques.fr/sites/all/themes/alternatives-economiques-main/assets/logo-alternatives-economiques.svg'
47
48 def is_article_url(self, url):
49 article_pattern = re.compile(r'/[^/]+/00\d{6}$')
50 return bool(article_pattern.search(url))
51
52 def parse_index(self):
53 articles = []
54 base_url = 'https://www.alternatives-economiques.fr'
55
56 thematiques = [
57 'biodiversite',
58 'ideesdebats',
59 'entreprise',
60 'europe',
61 'direct-de-recherche',
62 'asie',
63 'a-la-carte',
64 'chine',
65 'culture',
66 'des-idees-pour-sortir-de-la-crise',
67 'amerique-du-sud',
68 'idees-0',
69 'transport',
70 'services-publics',
71 'allemagne',
72 'face-a-face',
73 'politique-monetaire',
74 'logement',
75 'climat',
76 'innovation',
77 'agir',
78 'economie-sociale-et-solidaire',
79 'societe',
80 'theorie',
81 'revenus',
82 'tribune',
83 'conditions-de-travail',
84 'familles',
85 'politique',
86 'numerique',
87 'histoire',
88 'sociorama',
89 'mondialisation',
90 'opinions',
91 'consommation',
92 'dette',
93 'assurance-chomage',
94 'finance',
95 'temps-de-travail',
96 'emploi',
97 'protection-sociale',
98 'refugies',
99 'royaume-uni',
100 'conjoncture',
101 'population',
102 'libertes',
103 'jeunes',
104 'droit-du-travail',
105 'responsabilite-sociale',
106 'industrie',
107 'economie',
108 'ukraine',
109 'immigration',
110 'travail',
111 'etats-unis',
112 'inflation',
113 'relations-sociales',
114 'inegalites',
115 'management',
116 'energie',
117 'environnement',
118 'fiscalite',
119 'social',
120 'elections-europeennes',
121 'retraites',
122 'international',
123 'commerce-exterieur',
124 'sante',
125 'gestion',
126 'salaires',
127 'education',
128 'lanceurs-dalerte',
129 'japon',
130 'geopolitique',
131 'afrique',
132 'commerce',
133 'politiques-publiques',
134 'budget',
135 'grece',
136 'genre',
137 'services',
138 'pollution',
139 'agriculture',
140 'legislatives',
141 'chomage',
142 'graphorama',
143 'formation',
144 'budget-2025',
145 'territoires',
146 'espagne',
147 ]
148
149 special_sections = {'grands-formats': '/grands-formats', 'dessin': '/dessin'}
150
151 sections = {t: f'/thematiques/{t}' for t in thematiques}
152 sections.update(special_sections)
153
154 for section_name, section_path in sections.items():
155 url = f'{base_url}{section_path}'
156 self.log('Analyzing section:', url)
157 try:
158 soup = self.index_to_soup(url)
159 feed_articles = self.extract_articles(soup, base_url)
160 if feed_articles:
161 display_name = section_name.replace('-', ' ').title()
162 articles.append((display_name, feed_articles[: self.max_articles_per_feed]))
163 except Exception as e:
164 self.log.error(f'Error processing {section_name}: {e}')
165 continue
166
167 return articles
168
169 def extract_articles(self, soup, base_url):
170 feed_articles = []
171 processed_urls = set()
172
173 for link in soup.find_all('a', href=True):
174 article_url = link['href']
175 if self.is_article_url(article_url):
176 if not article_url.startswith('http'):
177 article_url = base_url + article_url
178
179 if article_url in processed_urls:
180 continue
181 processed_urls.add(article_url)
182
183 try:
184 article_soup = self.index_to_soup(article_url)
185 h1_title = article_soup.find('h1', class_='o-head__title')
186
187 if h1_title:
188 title = h1_title.get_text().strip()
189 else:
190 title_elem = link.find('h2')
191 if title_elem:
192 title = title_elem.get_text().strip()
193 else:
194 title = link.get_text().strip()
195 if not title:
196 title = article_url.split('/')[-2].replace('-', ' ').title()
197
198 if title:
199 feed_articles.append({'title': title, 'url': article_url, 'description': ''})
200 except Exception as e:
201 self.log.error(f'Error getting H1 title for {article_url}: {e}')
202 continue
203
204 return feed_articles
205
206 keep_only_tags = [
207 dict(name='h1', class_='o-head__title'),
208 dict(name='div', class_='chapo'),
209 dict(name='time', class_='o-infos__date-full'),
210 dict(name='div', class_='o-page__content__who'),
211 dict(name='div', class_='field-item even'),
212 dict(name='div', attrs={'property': 'content:encoded'}),
213 ]
214
215 remove_tags = [
216 dict(name=['script', 'style', 'iframe', 'svg', 'audio', 'video', 'button', 'form', 'input']),
217 dict(
218 name='div',
219 class_=[
220 'c-article__social',
221 'social-buttons',
222 'social-sharing',
223 'social-media',
224 'share-buttons',
225 'share-links',
226 'social-links',
227 'social-icons',
228 'embedded-content',
229 'embed-container',
230 'embed-wrapper',
231 'media-embed',
232 'twitter-embed',
233 'facebook-embed',
234 'social-embed',
235 'c-kiosk--single',
236 'c-comments',
237 'c-article__toolbar',
238 'c-article__related',
239 'c-epigraph',
240 'newsletter-signup',
241 'twitter-tweet',
242 'twitter-timeline',
243 'twitter-follow-button',
244 'c-footer__promo',
245 'o-page__block--offset--invert',
246 'newsletter-form',
247 'newsletter-block',
248 'newsletter',
249 'c-kiosk--single__content',
250 'c-kiosk--single__figure',
251 'c-kiosk--single__body',
252 'c-kiosk--single__cta',
253 'field-name-field-issue-cover',
254 ],
255 ),
256 ]
257
258 extra_css = '''
259 body { line-height: 1.6; margin: 1em; }
260 h1 { font-size: 1.8em; margin-bottom: 0.5em; font-weight: bold; }
261 .chapo { font-style: italic; margin: 1em 0; font-size: 1.2em; }
262 .o-infos__date-full { color: #666; margin: 0.5em 0; font-size: 0.9em; }
263 .o-page__content__who { color: #333; margin: 0.5em 0; font-weight: bold; }
264 p { margin: 0.8em 0; }
265
266 a {
267 text-decoration: none !important;
268 color: inherit !important;
269 }
270
271 .o-page__figure-full {
272 break-inside: avoid;
273 margin: 1em 0;
274 page-break-inside: avoid;
275 }
276 .o-page__figure-full figcaption {
277 font-style: italic;
278 text-align: center;
279 margin-top: 0.5em;
280 font-size: 0.9em;
281 color: #666;
282 }
283 '''
284
285 def preprocess_html(self, soup):
286 # Remove unwanted tags
287 for tag in soup.find_all(['script', 'style', 'iframe', 'svg', 'audio', 'video']):
288 tag.decompose()
289
290 # Clean attributes
291 for tag in soup.find_all(True):
292 if tag.name not in ['a', 'img']:
293 allowed_attrs = {'src', 'href', 'alt', 'title'}
294 tag.attrs = {k: v for k, v in tag.attrs.items() if k in allowed_attrs}
295
296 return soup