Debian Codegraph @

recipes/superinteressante.recipe

raw
1 import re
2
3 from calibre.web.feeds.news import BasicNewsRecipe
4
5
6 class SuperInteressante(BasicNewsRecipe):
7 title = 'Superinteressante: Revista'
8 description = 'Escolha uma edição específica ou baixe a mais recente.'
9 language = 'pt_BR'
10 __author__ = 'Pedro Souza'
11
12 recipe_specific_options = {
13 'edicao_numero': {'short': 'Número da edição', 'long': 'Digite o número da edição (ex: 485). Deixe em branco para a mais recente:', 'default': ''}
14 }
15
16 no_shortcuts = True
17 encoding = 'utf-8'
18 max_articles_per_feed = 100
19 simultaneous_downloads = 3
20 use_embedded_content = False
21 no_stylesheets = True
22 timeout = 30
23
24 # Desativa cache para forçar novo download sempre
25 no_favicon = True
26 ignore_duplicate_articles = {'title', 'url'}
27
28 keep_only_tags = [
29 dict(name='article'),
30 dict(name='div', attrs={'class': ['content-body', 'article-content', 'entry-content']}),
31 dict(name='header', attrs={'class': ['article-header']}),
32 ]
33
34 remove_tags = [
35 dict(name='div', attrs={'class': lambda x: x and any(c in x.split() for c in ['ads', 'post-ads', 'noreadme-audima', 'top-share'])}),
36 dict(name='div', attrs={'class': ['banner-container', 'trending', 'sidebar', 'social-share', 'tags', 'related-posts', 'newsletter-box']}),
37 dict(name='section', attrs={'class': ['newsletter', 'comments', 'recommended']}),
38 dict(name='footer'),
39 dict(name='nav'),
40 dict(name='script'),
41 dict(name='style'),
42 dict(name='aside'),
43 ]
44
45 def _get_edicao_input(self):
46 # O Calibre injeta o valor como atributo direto: self.edicao_numero
47 valor = getattr(self, 'edicao_numero', '') or getattr(self, 'edicao-numero', '')
48 if valor:
49 return str(valor).strip()
50
51 # Fallback: o Calibre pode ter substituído o dict pela string diretamente
52 opt = self.recipe_specific_options.get('edicao_numero', {})
53 if isinstance(opt, str):
54 return opt.strip()
55 if isinstance(opt, dict):
56 return opt.get('default', '').strip()
57
58 return ''
59
60 def parse_index(self):
61 edicao_input = self._get_edicao_input()
62 self.log(f'[DEBUG] Edição capturada: "{edicao_input}"')
63
64 if edicao_input and edicao_input.isdigit():
65 numero = edicao_input
66 # Muda o título para incluir a edição (mantém o prefixo)
67 self.title = f'Superinteressante: Edição {numero}'
68 issue_link = f'https://super.abril.com.br/superarquivo/{numero}/'
69 else:
70 self.title = 'Superinteressante: Última Edição'
71 self.log('Buscando edição mais recente...')
72 # Passa browser sem cache explicitamente
73 soup_arquivo = self.index_to_soup('https://super.abril.com.br/superarquivo/')
74 all_links = soup_arquivo.find_all('a', href=re.compile(r'/superarquivo/\d+/?$'))
75 if not all_links:
76 raise ValueError('Não foi possível localizar o arquivo.')
77 issue_link = all_links[0]['href']
78 if not issue_link.startswith('http'):
79 issue_link = 'https://super.abril.com.br' + issue_link
80
81 self.log(f'Baixando: {self.title} via {issue_link}')
82 soup_issue = self.index_to_soup(issue_link)
83
84 # CAPTURA DA CAPA
85 cover_div = soup_issue.find('div', attrs={'class': 'cover'})
86 if cover_div:
87 img_tag = cover_div.find('img')
88 if img_tag:
89 self.cover_url = img_tag.get('data-src') or img_tag.get('src')
90 if self.cover_url and ' ' in self.cover_url:
91 self.cover_url = self.cover_url.split(' ')[0].split(',')[0]
92
93 # CAPTURA DOS ARTIGOS
94 articles = []
95 found_links = soup_issue.select('a.list-item-link, .list-item a, .article-title a, h2 a')
96 seen_urls = set()
97
98 for link in found_links:
99 url = link.get('href')
100 if not url or not url.startswith(('http', '/')):
101 continue
102 if not url.startswith('http'):
103 url = 'https://super.abril.com.br' + url
104 if any(x in url for x in ['/facebook', '/twitter', '/whatsapp', '/tags/']):
105 continue
106 if url in seen_urls or url == issue_link:
107 continue
108
109 title = self.tag_to_string(link).strip()
110 if not title:
111 title_tag = link.find(['h2', 'h3', 'span'])
112 if title_tag:
113 title = self.tag_to_string(title_tag).strip()
114
115 if title and len(title) > 10:
116 articles.append({'title': title, 'url': url, 'description': '', 'date': ''})
117 seen_urls.add(url)
118
119 self.log(f'[DEBUG] Total de artigos encontrados: {len(articles)}')
120 return [('Matérias', articles)]
121
122 def get_browser(self):
123 br = BasicNewsRecipe.get_browser(self)
124 br.addheaders = [
125 ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'),
126 # Cabeçalhos anti-cache
127 ('Cache-Control', 'no-cache, no-store, must-revalidate'),
128 ('Pragma', 'no-cache'),
129 ('Expires', '0'),
130 ]
131 return br