Debian Codegraph @

recipes/le_canard_enchaine.recipe

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # Recette Calibre — Le Canard Enchaîné
4 # Auteur : Kabonix
5 # Le contenu premium est dans le HTML (CSS paywall) — pas besoin de login
6
7 from datetime import datetime, timedelta
8 from zoneinfo import ZoneInfo
9
10 from calibre.web.feeds.news import BasicNewsRecipe
11
12
13 class LeCanardEnchaine(BasicNewsRecipe):
14 title = 'Le Canard Enchaîné'
15 __author__ = 'Kabonix'
16 description = 'Articles du Canard Enchaîné (sans login — CSS paywall)'
17 language = 'fr'
18 no_stylesheets = True
19 auto_cleanup = False
20 remove_javascript = True
21 max_image_width = 600
22 max_image_height = 800
23
24 # Spoofer le referer Google pour contourner le paywall CSS
25 # Googlebot spoof — le Canard sert le contenu complet aux robots Google (pour indexation)
26 browser_user_agent = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
27
28 def get_browser(self, *args, **kwargs):
29 br = BasicNewsRecipe.get_browser(self, *args, **kwargs)
30 br.set_handle_robots(False)
31 br.addheaders = [
32 ('User-Agent', self.browser_user_agent),
33 ('Referer', 'https://www.google.fr/'),
34 ('X-Forwarded-For', '66.249.66.1'), # IP officielle Googlebot
35 ('Accept-Language', 'fr-FR,fr;q=0.9'),
36 ]
37 return br
38
39 # ------------------------------------------------------------------ #
40 # Couverture — scraping page boutique #
41 # ------------------------------------------------------------------ #
42 def get_cover_url(self):
43 try:
44 br = self.get_browser()
45 soup = self.index_to_soup(br.open('https://boutique.lecanardenchaine.fr/acheter-au-numero/').read())
46 li = soup.find('li', {'class': 'list-item'})
47 if li:
48 img = li.find('img')
49 if img and img.get('srcset'):
50 return 'https://boutique.lecanardenchaine.fr' + img['srcset'].split()[0]
51 if img and img.get('src'):
52 return 'https://boutique.lecanardenchaine.fr' + img['src']
53 except Exception:
54 pass
55 return 'https://image.ausha.co/2x1H3rkhwjmSwAa8KzIFfcN0G9GxfJWY83UafXn8_400x400.jpeg'
56
57 # ------------------------------------------------------------------ #
58 # Sélection du contenu #
59 # ------------------------------------------------------------------ #
60 keep_only_tags = [
61 dict(name='div', attrs={'class': 'article__heading'}),
62 dict(name='div', attrs={'class': 'editorial'}),
63 ]
64
65 remove_tags = [
66 dict(name=['script', 'style', 'nav', 'header', 'footer', 'button', 'form']),
67 dict(
68 name='div',
69 attrs={
70 'class': [
71 'share-mobile',
72 'share-sticky',
73 'article__author',
74 'article__tags',
75 'list-breadcrumb',
76 'modal',
77 ]
78 },
79 ),
80 ]
81
82 extra_css = '''
83 h1, h2 { font-size: 1.2em !important; font-weight: bold; }
84 .editorial__chapo { font-style: italic; margin-bottom: 1em; }
85 p { line-height: 1.5; }
86 a { color: black !important; text-decoration: none !important; }
87 .zoom { border-left: 3px solid #ccc; padding-left: 1em; margin: 1em 0; }
88 '''
89
90 # ------------------------------------------------------------------ #
91 # Le bypass CSS paywall : on vire juste la classe paywall #
92 # Le contenu est déjà dans le HTML — c'est un CSS paywall pur #
93 # ------------------------------------------------------------------ #
94 def preprocess_html(self, soup):
95 # Déverrouiller le contenu caché par CSS
96 for div in soup.findAll('div', attrs={'id': 'paywall'}):
97 div['class'] = ''
98 div['id'] = ''
99 for div in soup.findAll('div', attrs={'class': 'paywall'}):
100 div['class'] = ''
101 # Nettoyer les overlays de paywall
102 for div in soup.findAll('div', attrs={'class': 'non-paywall'}):
103 div['class'] = ''
104 return soup
105
106 def postprocess_html(self, soup, first_fetch):
107 for tag in soup.findAll(True):
108 for attr in list(tag.attrs):
109 if attr not in ['href', 'src', 'class']:
110 del tag[attr]
111 return soup
112
113 # ------------------------------------------------------------------ #
114 # Index des sections #
115 # ------------------------------------------------------------------ #
116 SECTIONS = {
117 'Politique': '/politique/',
118 'Économie': '/economie/',
119 'International': '/international/',
120 'Défense': '/defense/',
121 'Société': '/societe/',
122 'Police-Justice': '/police-justice/',
123 'Santé': '/sante/',
124 'Éducation': '/education/',
125 'Environnement': '/environnement/',
126 'Technologie-Sciences': '/technologie-sciences/',
127 'Culture-Idées': '/culture-idees/',
128 'Médias': '/medias/',
129 'Sport': '/sport/',
130 'Social': '/social/',
131 'Brèves': '/breves/',
132 }
133
134 def parse_index(self):
135 br = self.get_browser()
136 feeds = []
137 today = datetime.now(ZoneInfo('Europe/Paris'))
138 week_ago = today - timedelta(days=7)
139
140 for section_title, section_url in self.SECTIONS.items():
141 articles = []
142 try:
143 url = 'https://www.lecanardenchaine.fr' + section_url
144 soup = self.index_to_soup(br.open(url).read())
145
146 for article in soup.findAll('article', {'class': 'article-item'}):
147 link = article.find('a', href=True)
148 date_div = article.find('div', {'class': 'article-item__date'})
149
150 if not (link and date_div):
151 continue
152
153 href = link['href']
154 title = link.get_text(separator=' ').strip()
155 time_element = date_div.find('time')
156
157 if not (time_element and time_element.get('datetime')):
158 continue
159
160 article_date = datetime.fromisoformat(time_element['datetime'])
161 if article_date.date() <= week_ago.date():
162 continue
163
164 if not href.startswith('http'):
165 href = 'https://www.lecanardenchaine.fr' + href
166
167 articles.append({
168 'title': title,
169 'url': href,
170 'description': f"Publié le {article_date.strftime('%d/%m/%Y')}",
171 'date': article_date.strftime('%a, %d %b %Y %H:%M:%S %z'),
172 })
173
174 except Exception as e:
175 self.log.warning(f'Erreur sur {section_title}: {e}')
176
177 if articles:
178 feeds.append((section_title, articles))
179
180 if not feeds:
181 raise ValueError('Aucun article trouvé')
182 return feeds