Debian Codegraph @

recipes/newsweek_polska.recipe

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from __future__ import print_function
5
6 __license__ = 'GPL v3'
7 __copyright__ = '2010, matek09, [email protected]; 2012-2013, admroz, [email protected]'
8
9 import datetime
10 import re
11 from string import capwords
12
13 from calibre.ebooks.BeautifulSoup import BeautifulSoup
14 from calibre.ptempfile import PersistentTemporaryFile
15 from calibre.web.feeds.news import BasicNewsRecipe
16
17
18 class Newsweek(BasicNewsRecipe):
19 # how many issues to go back, 0 means get the most current one
20 BACK_ISSUES = 1
21
22 EDITION = '0'
23 DATE = None
24 YEAR = datetime.datetime.now().year
25
26 title = 'Newsweek Polska'
27 __author__ = 'matek09, admroz'
28 description = 'Weekly magazine'
29 encoding = 'utf-8'
30 language = 'pl'
31 remove_javascript = True
32
33 temp_files = []
34 articles_are_obfuscated = True
35
36 #
37 # Parses article contents from one page
38 #
39 def get_article_divs(self, css, main_section):
40 strs = []
41
42 # get all divs with given css class
43 article_divs = main_section.findAll('div', attrs={'class': css})
44 for article_div in article_divs:
45 # remove sections like 'read more...' etc.
46 for p in article_div.findAll('p'):
47 if p.find('span', attrs={'style': 'color: #800000; font-size: medium;'}):
48 p.extract()
49 continue
50
51 if p.find('span', attrs={'style': 'font-size: medium; color: #800000;'}):
52 p.extract()
53 continue
54
55 if p.find('span', attrs={'style': 'font-size: medium;'}):
56 p.extract()
57 continue
58
59 if p.find('span', attrs={'style': 'color: #800000;'}):
60 p.extract()
61 continue
62
63 obj = p.find('object')
64 if obj:
65 obj.extract()
66 continue
67
68 strong = p.find('strong')
69 if strong:
70 newest = re.compile(r'Tekst pochodzi z najnowszego numeru Tygodnika Newsweek')
71 if newest.search(str(strong)):
72 strong.extract()
73 continue
74
75 itunes = p.find('a')
76 if itunes:
77 reurl = re.compile(r'itunes.apple.com')
78 if reurl.search(str(itunes['href'])):
79 p.extract()
80 continue
81
82 imagedesc = p.find('div', attrs={'class': 'image-desc'})
83 if imagedesc:
84 redesc = re.compile(r'Okładka numeru')
85 if redesc.search(str(imagedesc)):
86 p.extract()
87 continue
88
89 # get actual contents
90 for content in article_div.contents:
91 strs.append(''.join(str(content)))
92
93 # return contents as a string
94 return ''.join(strs)
95
96 #
97 # Articles can be divided into several pages, this method parses them recursevely
98 #
99 def get_article_page(self, br, url, page):
100 br.open(url)
101 source = br.response().read()
102
103 html = ''
104
105 matches = re.search(r'<article>(.*)</article>', source, re.DOTALL)
106 if matches is None:
107 print('no article tag found, returning...')
108 return
109
110 main_section = BeautifulSoup(matches.group(0))
111
112 if page == 0:
113 title = main_section.find('h1')
114 html = html + type('')(title)
115
116 authors = ''
117 authorBox = main_section.find('div', attrs={'class': 'AuthorBox'})
118 if authorBox is not None:
119 authorH4 = authorBox.find('h4')
120 if authorH4 is not None:
121 authors = self.tag_to_string(authorH4)
122 html = html + type('')(authors)
123
124 info = main_section.find('p', attrs={'class': 'lead'})
125 html = html + type('')(info)
126
127 html = html + self.get_article_divs('3917dc34e07c9c7180df2ea9ef103361845c8af42b71f51b960059226090a1ac articleStart', main_section)
128 html = html + self.get_article_divs('3917dc34e07c9c7180df2ea9ef103361845c8af42b71f51b960059226090a1ac', main_section)
129
130 nextPage = main_section.find('a', attrs={'class': 'next'})
131 if nextPage:
132 html = html + self.get_article_page(br, nextPage['href'], page + 1)
133
134 return html
135
136 #
137 # Parses each article
138 #
139 def get_obfuscated_article(self, url):
140 br = self.get_browser()
141 html = self.get_article_page(br, url, 0)
142 self.temp_files.append(PersistentTemporaryFile('_temparse.html'))
143 self.temp_files[-1].write(html)
144 self.temp_files[-1].close()
145 return self.temp_files[-1].name
146
147 #
148 # Goes back given number of issues. It also knows how to go back
149 # to the previous year if there are not enough issues in the current one
150 #
151 def find_last_issue(self, archive_url):
152 archive_soup = self.index_to_soup(archive_url, True)
153
154 # workaround because html is so messed up that find() method on soup returns None
155 # and therefore we need to extract subhtml that we need
156 matches = re.search(r'<ul class="rightIssueList">(.*?)</ul>', archive_soup, re.DOTALL)
157 if matches is None:
158 return
159
160 subSoup = BeautifulSoup(matches.group(0))
161 issueLinks = subSoup.findAll('a')
162
163 # check if need to go back to previous year
164 if len(issueLinks) > self.BACK_ISSUES:
165 link = issueLinks[self.BACK_ISSUES]
166 self.EDITION = link['href'].replace('http://www.newsweek.pl/wydania/', '')
167 self.index_to_soup('http://www.newsweek.pl/wydania/' + self.EDITION)
168 else:
169 self.BACK_ISSUES = self.BACK_ISSUES - len(issueLinks)
170 self.YEAR = self.YEAR - 1
171 self.find_last_issue(archive_url + '/' + str(self.YEAR))
172
173 #
174 # Looks for the last issue which we want to download. Then goes on each
175 # section and article and stores them (assigning to sections)
176 #
177 def parse_index(self):
178 archive_url = 'http://www.newsweek.pl/wydania/archiwum'
179 self.find_last_issue(archive_url)
180 soup = self.index_to_soup('http://www.newsweek.pl/wydania/' + self.EDITION)
181
182 matches = re.search(r'<div class="Issue-Entry">(.*)ARTICLE_BOTTOM', soup.prettify(), re.DOTALL)
183 if matches is None:
184 return
185
186 main_section = BeautifulSoup(matches.group(0))
187
188 # date
189 matches = re.search(r'(\d{2}-\d{2}-\d{4})', self.tag_to_string(main_section.find('h2')))
190 if matches:
191 self.DATE = matches.group(0)
192
193 # cover
194 img = main_section.find('img', src=True, alt=True, title=True)
195 self.cover_url = img['src']
196 feeds = []
197 articles = {}
198 sections = []
199
200 # sections
201 for sectionUl in main_section.findAll('ul', attrs={'class': 'whatsin'}):
202 # section header
203 header = sectionUl.find('li', attrs={'class': 'header'})
204 if header is None:
205 continue
206
207 section = capwords(self.tag_to_string(header))
208
209 # articles in section
210 articleUl = sectionUl.find('ul')
211 if articleUl is None:
212 continue
213
214 for articleLi in articleUl.findAll('li'):
215 # check if article is closed which should be skipped
216 closed = articleLi.find('span', attrs={'class': 'closeart'})
217 if closed is not None:
218 continue
219
220 article = self.create_article(articleLi)
221 if article is None:
222 continue
223
224 if section in articles:
225 articles[section].append(article)
226 else:
227 articles[section] = [article]
228 sections.append(section)
229
230 for section in sections:
231 # print("%s -> %d" % (section, len(articles[section])))
232 #
233 # for article in articles[section]:
234 # print(" - %s" % article)
235
236 feeds.append((section, articles[section]))
237
238 return feeds
239
240 #
241 # Creates each article metadata (skips locked ones). The content will
242 # be extracted later by other method (get_obfuscated_article).
243 #
244 def create_article(self, articleLi):
245 article = {}
246
247 a = articleLi.find('a')
248 if a is None:
249 return None
250
251 article['title'] = self.tag_to_string(a)
252 article['url'] = a['href']
253 article['date'] = self.DATE
254 article['description'] = ''
255
256 return article