PageRenderTime 78ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/imdb/parser/http/movieParser.py

https://bitbucket.org/alberanid/imdbpy/
Python | 1951 lines | 1909 code | 19 blank | 23 comment | 23 complexity | c9223950c96d878cfa96a8fd8e0a796d MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. """
  2. parser.http.movieParser module (imdb package).
  3. This module provides the classes (and the instances), used to parse the
  4. IMDb pages on the akas.imdb.com server about a movie.
  5. E.g., for Brian De Palma's "The Untouchables", the referred
  6. pages would be:
  7. combined details: http://akas.imdb.com/title/tt0094226/combined
  8. plot summary: http://akas.imdb.com/title/tt0094226/plotsummary
  9. ...and so on...
  10. Copyright 2004-2016 Davide Alberani <da@erlug.linux.it>
  11. 2008 H. Turgut Uyar <uyar@tekir.org>
  12. This program is free software; you can redistribute it and/or modify
  13. it under the terms of the GNU General Public License as published by
  14. the Free Software Foundation; either version 2 of the License, or
  15. (at your option) any later version.
  16. This program is distributed in the hope that it will be useful,
  17. but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. GNU General Public License for more details.
  20. You should have received a copy of the GNU General Public License
  21. along with this program; if not, write to the Free Software
  22. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  23. """
  24. import re
  25. import urllib
  26. from imdb import imdbURL_base
  27. from imdb.Person import Person
  28. from imdb.Movie import Movie
  29. from imdb.Company import Company
  30. from imdb.utils import analyze_title, split_company_name_notes, _Container
  31. from utils import build_person, DOMParserBase, Attribute, Extractor, \
  32. analyze_imdbid
  33. # Dictionary used to convert some section's names.
  34. _SECT_CONV = {
  35. 'directed': 'director',
  36. 'directed by': 'director',
  37. 'directors': 'director',
  38. 'editors': 'editor',
  39. 'writing credits': 'writer',
  40. 'writers': 'writer',
  41. 'produced': 'producer',
  42. 'cinematography': 'cinematographer',
  43. 'film editing': 'editor',
  44. 'casting': 'casting director',
  45. 'costume design': 'costume designer',
  46. 'makeup department': 'make up',
  47. 'production management': 'production manager',
  48. 'second unit director or assistant director': 'assistant director',
  49. 'costume and wardrobe department': 'costume department',
  50. 'sound department': 'sound crew',
  51. 'stunts': 'stunt performer',
  52. 'other crew': 'miscellaneous crew',
  53. 'also known as': 'akas',
  54. 'country': 'countries',
  55. 'runtime': 'runtimes',
  56. 'language': 'languages',
  57. 'certification': 'certificates',
  58. 'genre': 'genres',
  59. 'created': 'creator',
  60. 'creators': 'creator',
  61. 'color': 'color info',
  62. 'plot': 'plot outline',
  63. 'seasons': 'number of seasons',
  64. 'art directors': 'art direction',
  65. 'assistant directors': 'assistant director',
  66. 'set decorators': 'set decoration',
  67. 'visual effects department': 'visual effects',
  68. 'production managers': 'production manager',
  69. 'miscellaneous': 'miscellaneous crew',
  70. 'make up department': 'make up',
  71. 'plot summary': 'plot outline',
  72. 'cinematographers': 'cinematographer',
  73. 'camera department': 'camera and electrical department',
  74. 'costume designers': 'costume designer',
  75. 'production designers': 'production design',
  76. 'production managers': 'production manager',
  77. 'music original': 'original music',
  78. 'casting directors': 'casting director',
  79. 'other companies': 'miscellaneous companies',
  80. 'producers': 'producer',
  81. 'special effects by': 'special effects department',
  82. 'special effects': 'special effects companies'
  83. }
  84. def _manageRoles(mo):
  85. """Perform some transformation on the html, so that roleIDs can
  86. be easily retrieved."""
  87. firstHalf = mo.group(1)
  88. secondHalf = mo.group(2)
  89. newRoles = []
  90. roles = secondHalf.split(' / ')
  91. for role in roles:
  92. role = role.strip()
  93. if not role:
  94. continue
  95. roleID = analyze_imdbid(role)
  96. if roleID is None:
  97. roleID = u'/'
  98. else:
  99. roleID += u'/'
  100. newRoles.append(u'<div class="_imdbpyrole" roleid="%s">%s</div>' % \
  101. (roleID, role.strip()))
  102. return firstHalf + u' / '.join(newRoles) + mo.group(3)
  103. _reRolesMovie = re.compile(r'(<td class="char">)(.*?)(</td>)',
  104. re.I | re.M | re.S)
  105. def _replaceBR(mo):
  106. """Replaces <br> tags with '::' (useful for some akas)"""
  107. txt = mo.group(0)
  108. return txt.replace('<br>', '::')
  109. _reAkas = re.compile(r'<h5>also known as:</h5>.*?</div>', re.I | re.M | re.S)
  110. def makeSplitter(lstrip=None, sep='|', comments=True,
  111. origNotesSep=' (', newNotesSep='::(', strip=None):
  112. """Return a splitter function suitable for a given set of data."""
  113. def splitter(x):
  114. if not x: return x
  115. x = x.strip()
  116. if not x: return x
  117. if lstrip is not None:
  118. x = x.lstrip(lstrip).lstrip()
  119. lx = x.split(sep)
  120. lx[:] = filter(None, [j.strip() for j in lx])
  121. if comments:
  122. lx[:] = [j.replace(origNotesSep, newNotesSep, 1) for j in lx]
  123. if strip:
  124. lx[:] = [j.strip(strip) for j in lx]
  125. return lx
  126. return splitter
  127. def _toInt(val, replace=()):
  128. """Return the value, converted to integer, or None; if present, 'replace'
  129. must be a list of tuples of values to replace."""
  130. for before, after in replace:
  131. val = val.replace(before, after)
  132. try:
  133. return int(val)
  134. except (TypeError, ValueError):
  135. return None
  136. class DOMHTMLMovieParser(DOMParserBase):
  137. """Parser for the "combined details" (and if instance.mdparse is
  138. True also for the "main details") page of a given movie.
  139. The page should be provided as a string, as taken from
  140. the akas.imdb.com server. The final result will be a
  141. dictionary, with a key for every relevant section.
  142. Example:
  143. mparser = DOMHTMLMovieParser()
  144. result = mparser.parse(combined_details_html_string)
  145. """
  146. _containsObjects = True
  147. extractors = [Extractor(label='title',
  148. path="//h1",
  149. attrs=Attribute(key='title',
  150. path=".//text()",
  151. postprocess=analyze_title)),
  152. Extractor(label='glossarysections',
  153. group="//a[@class='glossary']",
  154. group_key="./@name",
  155. group_key_normalize=lambda x: x.replace('_', ' '),
  156. path="../../../..//tr",
  157. attrs=Attribute(key=None,
  158. multi=True,
  159. path={'person': ".//text()",
  160. 'link': "./td[1]/a[@href]/@href"},
  161. postprocess=lambda x: \
  162. build_person(x.get('person') or u'',
  163. personID=analyze_imdbid(x.get('link')))
  164. )),
  165. Extractor(label='cast',
  166. path="//table[@class='cast']//tr",
  167. attrs=Attribute(key="cast",
  168. multi=True,
  169. path={'person': ".//text()",
  170. 'link': "td[2]/a/@href",
  171. 'roleID': \
  172. "td[4]/div[@class='_imdbpyrole']/@roleid"},
  173. postprocess=lambda x: \
  174. build_person(x.get('person') or u'',
  175. personID=analyze_imdbid(x.get('link')),
  176. roleID=(x.get('roleID') or u'').split('/'))
  177. )),
  178. Extractor(label='genres',
  179. path="//div[@class='info']//a[starts-with(@href," \
  180. " '/Sections/Genres')]",
  181. attrs=Attribute(key="genres",
  182. multi=True,
  183. path="./text()")),
  184. Extractor(label='myrating',
  185. path="//span[@id='voteuser']",
  186. attrs=Attribute(key='myrating',
  187. path=".//text()")),
  188. Extractor(label='h5sections',
  189. path="//div[@class='info']/h5/..",
  190. attrs=[
  191. Attribute(key="plot summary",
  192. path="./h5[starts-with(text(), " \
  193. "'Plot:')]/../div/text()",
  194. postprocess=lambda x: \
  195. x.strip().rstrip('|').rstrip()),
  196. Attribute(key="aspect ratio",
  197. path="./h5[starts-with(text()," \
  198. " 'Aspect')]/../div/text()",
  199. postprocess=lambda x: x.strip()),
  200. Attribute(key="mpaa",
  201. path="./h5/a[starts-with(text()," \
  202. " 'MPAA')]/../../div/text()",
  203. postprocess=lambda x: x.strip()),
  204. Attribute(key="countries",
  205. path="./h5[starts-with(text(), " \
  206. "'Countr')]/../div[@class='info-content']//text()",
  207. postprocess=makeSplitter('|')),
  208. Attribute(key="language",
  209. path="./h5[starts-with(text(), " \
  210. "'Language')]/..//text()",
  211. postprocess=makeSplitter('Language:')),
  212. Attribute(key='color info',
  213. path="./h5[starts-with(text(), " \
  214. "'Color')]/..//text()",
  215. postprocess=makeSplitter('|')),
  216. Attribute(key='sound mix',
  217. path="./h5[starts-with(text(), " \
  218. "'Sound Mix')]/..//text()",
  219. postprocess=makeSplitter('Sound Mix:')),
  220. # Collects akas not encosed in <i> tags.
  221. Attribute(key='other akas',
  222. path="./h5[starts-with(text(), " \
  223. "'Also Known As')]/../div//text()",
  224. postprocess=makeSplitter(sep='::',
  225. origNotesSep='" - ',
  226. newNotesSep='::',
  227. strip='"')),
  228. Attribute(key='runtimes',
  229. path="./h5[starts-with(text(), " \
  230. "'Runtime')]/../div/text()",
  231. postprocess=makeSplitter()),
  232. Attribute(key='certificates',
  233. path="./h5[starts-with(text(), " \
  234. "'Certificat')]/..//text()",
  235. postprocess=makeSplitter('Certification:')),
  236. Attribute(key='number of seasons',
  237. path="./h5[starts-with(text(), " \
  238. "'Seasons')]/..//text()",
  239. postprocess=lambda x: x.count('|') + 1),
  240. Attribute(key='original air date',
  241. path="./h5[starts-with(text(), " \
  242. "'Original Air Date')]/../div/text()"),
  243. Attribute(key='tv series link',
  244. path="./h5[starts-with(text(), " \
  245. "'TV Series')]/..//a/@href"),
  246. Attribute(key='tv series title',
  247. path="./h5[starts-with(text(), " \
  248. "'TV Series')]/..//a/text()")
  249. ]),
  250. Extractor(label='language codes',
  251. path="//h5[starts-with(text(), 'Language')]/..//a[starts-with(@href, '/language/')]",
  252. attrs=Attribute(key='language codes', multi=True,
  253. path="./@href",
  254. postprocess=lambda x: x.split('/')[2].strip()
  255. )),
  256. Extractor(label='country codes',
  257. path="//h5[starts-with(text(), 'Country')]/..//a[starts-with(@href, '/country/')]",
  258. attrs=Attribute(key='country codes', multi=True,
  259. path="./@href",
  260. postprocess=lambda x: x.split('/')[2].strip()
  261. )),
  262. Extractor(label='creator',
  263. path="//h5[starts-with(text(), 'Creator')]/..//a",
  264. attrs=Attribute(key='creator', multi=True,
  265. path={'name': "./text()",
  266. 'link': "./@href"},
  267. postprocess=lambda x: \
  268. build_person(x.get('name') or u'',
  269. personID=analyze_imdbid(x.get('link')))
  270. )),
  271. Extractor(label='thin writer',
  272. path="//h5[starts-with(text(), 'Writer')]/..//a",
  273. attrs=Attribute(key='thin writer', multi=True,
  274. path={'name': "./text()",
  275. 'link': "./@href"},
  276. postprocess=lambda x: \
  277. build_person(x.get('name') or u'',
  278. personID=analyze_imdbid(x.get('link')))
  279. )),
  280. Extractor(label='thin director',
  281. path="//h5[starts-with(text(), 'Director')]/..//a",
  282. attrs=Attribute(key='thin director', multi=True,
  283. path={'name': "./text()",
  284. 'link': "@href"},
  285. postprocess=lambda x: \
  286. build_person(x.get('name') or u'',
  287. personID=analyze_imdbid(x.get('link')))
  288. )),
  289. Extractor(label='top 250/bottom 100',
  290. path="//div[@class='starbar-special']/" \
  291. "a[starts-with(@href, '/chart/')]",
  292. attrs=Attribute(key='top/bottom rank',
  293. path="./text()")),
  294. Extractor(label='series years',
  295. path="//div[@id='tn15title']//span" \
  296. "[starts-with(text(), 'TV series')]",
  297. attrs=Attribute(key='series years',
  298. path="./text()",
  299. postprocess=lambda x: \
  300. x.replace('TV series','').strip())),
  301. Extractor(label='number of episodes',
  302. path="//a[@title='Full Episode List']",
  303. attrs=Attribute(key='number of episodes',
  304. path="./text()",
  305. postprocess=lambda x: \
  306. _toInt(x, [(' Episodes', '')]))),
  307. Extractor(label='akas',
  308. path="//i[@class='transl']",
  309. attrs=Attribute(key='akas', multi=True, path='text()',
  310. postprocess=lambda x:
  311. x.replace(' ', ' ').rstrip('-').replace('" - ',
  312. '"::', 1).strip('"').replace(' ', ' '))),
  313. Extractor(label='production notes/status',
  314. path="//h5[starts-with(text(), 'Status:')]/..//div[@class='info-content']",
  315. attrs=Attribute(key='production status',
  316. path=".//text()",
  317. postprocess=lambda x: x.strip().split('|')[0].strip().lower())),
  318. Extractor(label='production notes/status updated',
  319. path="//h5[starts-with(text(), 'Status Updated:')]/..//div[@class='info-content']",
  320. attrs=Attribute(key='production status updated',
  321. path=".//text()",
  322. postprocess=lambda x: x.strip())),
  323. Extractor(label='production notes/comments',
  324. path="//h5[starts-with(text(), 'Comments:')]/..//div[@class='info-content']",
  325. attrs=Attribute(key='production comments',
  326. path=".//text()",
  327. postprocess=lambda x: x.strip())),
  328. Extractor(label='production notes/note',
  329. path="//h5[starts-with(text(), 'Note:')]/..//div[@class='info-content']",
  330. attrs=Attribute(key='production note',
  331. path=".//text()",
  332. postprocess=lambda x: x.strip())),
  333. Extractor(label='blackcatheader',
  334. group="//b[@class='blackcatheader']",
  335. group_key="./text()",
  336. group_key_normalize=lambda x: x.lower(),
  337. path="../ul/li",
  338. attrs=Attribute(key=None,
  339. multi=True,
  340. path={'name': "./a//text()",
  341. 'comp-link': "./a/@href",
  342. 'notes': "./text()"},
  343. postprocess=lambda x: \
  344. Company(name=x.get('name') or u'',
  345. companyID=analyze_imdbid(x.get('comp-link')),
  346. notes=(x.get('notes') or u'').strip())
  347. )),
  348. Extractor(label='rating',
  349. path="//div[@class='starbar-meta']/b",
  350. attrs=Attribute(key='rating',
  351. path=".//text()")),
  352. Extractor(label='votes',
  353. path="//div[@class='starbar-meta']/a[@href]",
  354. attrs=Attribute(key='votes',
  355. path=".//text()")),
  356. Extractor(label='cover url',
  357. path="//a[@name='poster']",
  358. attrs=Attribute(key='cover url',
  359. path="./img/@src"))
  360. ]
  361. preprocessors = [
  362. (re.compile(r'(<b class="blackcatheader">.+?</b>)', re.I),
  363. r'</div><div>\1'),
  364. ('<small>Full cast and crew for<br>', ''),
  365. ('<td> </td>', '<td>...</td>'),
  366. ('<span class="tv-extra">TV mini-series</span>',
  367. '<span class="tv-extra">(mini)</span>'),
  368. (_reRolesMovie, _manageRoles),
  369. (_reAkas, _replaceBR)]
  370. def preprocess_dom(self, dom):
  371. # Handle series information.
  372. xpath = self.xpath(dom, "//b[text()='Series Crew']")
  373. if xpath:
  374. b = xpath[-1] # In doubt, take the last one.
  375. for a in self.xpath(b, "./following::h5/a[@class='glossary']"):
  376. name = a.get('name')
  377. if name:
  378. a.set('name', 'series %s' % name)
  379. # Remove links to IMDbPro.
  380. for proLink in self.xpath(dom, "//span[@class='pro-link']"):
  381. proLink.drop_tree()
  382. # Remove some 'more' links (keep others, like the one around
  383. # the number of votes).
  384. for tn15more in self.xpath(dom,
  385. "//a[@class='tn15more'][starts-with(@href, '/title/')]"):
  386. tn15more.drop_tree()
  387. return dom
  388. re_space = re.compile(r'\s+')
  389. re_airdate = re.compile(r'(.*)\s*\(season (\d+), episode (\d+)\)', re.I)
  390. def postprocess_data(self, data):
  391. # Convert section names.
  392. for sect in data.keys():
  393. if sect in _SECT_CONV:
  394. data[_SECT_CONV[sect]] = data[sect]
  395. del data[sect]
  396. sect = _SECT_CONV[sect]
  397. # Filter out fake values.
  398. for key in data:
  399. value = data[key]
  400. if isinstance(value, list) and value:
  401. if isinstance(value[0], Person):
  402. data[key] = filter(lambda x: x.personID is not None, value)
  403. if isinstance(value[0], _Container):
  404. for obj in data[key]:
  405. obj.accessSystem = self._as
  406. obj.modFunct = self._modFunct
  407. if 'akas' in data or 'other akas' in data:
  408. akas = data.get('akas') or []
  409. other_akas = data.get('other akas') or []
  410. akas += other_akas
  411. nakas = []
  412. for aka in akas:
  413. aka = aka.strip()
  414. if aka.endswith('" -'):
  415. aka = aka[:-3].rstrip()
  416. nakas.append(aka)
  417. if 'akas' in data:
  418. del data['akas']
  419. if 'other akas' in data:
  420. del data['other akas']
  421. if nakas:
  422. data['akas'] = nakas
  423. if 'color info' in data:
  424. data['color info'] = [x.replace('Color:', '', 1) for x in data['color info']]
  425. if 'runtimes' in data:
  426. data['runtimes'] = [x.replace(' min', u'')
  427. for x in data['runtimes']]
  428. if 'original air date' in data:
  429. oid = self.re_space.sub(' ', data['original air date']).strip()
  430. data['original air date'] = oid
  431. aid = self.re_airdate.findall(oid)
  432. if aid and len(aid[0]) == 3:
  433. date, season, episode = aid[0]
  434. date = date.strip()
  435. try: season = int(season)
  436. except: pass
  437. try: episode = int(episode)
  438. except: pass
  439. if date and date != '????':
  440. data['original air date'] = date
  441. else:
  442. del data['original air date']
  443. # Handle also "episode 0".
  444. if season or type(season) is type(0):
  445. data['season'] = season
  446. if episode or type(season) is type(0):
  447. data['episode'] = episode
  448. for k in ('writer', 'director'):
  449. t_k = 'thin %s' % k
  450. if t_k not in data:
  451. continue
  452. if k not in data:
  453. data[k] = data[t_k]
  454. del data[t_k]
  455. if 'top/bottom rank' in data:
  456. tbVal = data['top/bottom rank'].lower()
  457. if tbVal.startswith('top'):
  458. tbKey = 'top 250 rank'
  459. tbVal = _toInt(tbVal, [('top 250: #', '')])
  460. else:
  461. tbKey = 'bottom 100 rank'
  462. tbVal = _toInt(tbVal, [('bottom 100: #', '')])
  463. if tbVal:
  464. data[tbKey] = tbVal
  465. del data['top/bottom rank']
  466. if 'year' in data and data['year'] == '????':
  467. del data['year']
  468. if 'tv series link' in data:
  469. if 'tv series title' in data:
  470. data['episode of'] = Movie(title=data['tv series title'],
  471. movieID=analyze_imdbid(
  472. data['tv series link']),
  473. accessSystem=self._as,
  474. modFunct=self._modFunct)
  475. del data['tv series title']
  476. del data['tv series link']
  477. if 'rating' in data:
  478. try:
  479. data['rating'] = float(data['rating'].replace('/10', ''))
  480. except (TypeError, ValueError):
  481. pass
  482. if 'votes' in data:
  483. try:
  484. votes = data['votes'].replace(',', '').replace('votes', '')
  485. data['votes'] = int(votes)
  486. except (TypeError, ValueError):
  487. pass
  488. return data
  489. def _process_plotsummary(x):
  490. """Process a plot (contributed by Rdian06)."""
  491. xauthor = x.get('author')
  492. xplot = x.get('plot', u'').strip()
  493. if xauthor:
  494. xplot += u'::%s' % xauthor
  495. return xplot
  496. class DOMHTMLPlotParser(DOMParserBase):
  497. """Parser for the "plot summary" page of a given movie.
  498. The page should be provided as a string, as taken from
  499. the akas.imdb.com server. The final result will be a
  500. dictionary, with a 'plot' key, containing a list
  501. of string with the structure: 'summary::summary_author <author@email>'.
  502. Example:
  503. pparser = HTMLPlotParser()
  504. result = pparser.parse(plot_summary_html_string)
  505. """
  506. _defGetRefs = True
  507. # Notice that recently IMDb started to put the email of the
  508. # author only in the link, that we're not collecting, here.
  509. extractors = [Extractor(label='plot',
  510. path="//ul[@class='zebraList']//p",
  511. attrs=Attribute(key='plot',
  512. multi=True,
  513. path={'plot': './text()[1]',
  514. 'author': './span/em/a/text()'},
  515. postprocess=_process_plotsummary))]
  516. def _process_award(x):
  517. award = {}
  518. _award = x.get('award')
  519. if _award is not None:
  520. _award = _award.strip()
  521. award['award'] = _award
  522. if not award['award']:
  523. return {}
  524. award['year'] = x.get('year').strip()
  525. if award['year'] and award['year'].isdigit():
  526. award['year'] = int(award['year'])
  527. award['result'] = x.get('result').strip()
  528. category = x.get('category').strip()
  529. if category:
  530. award['category'] = category
  531. received_with = x.get('with')
  532. if received_with is not None:
  533. award['with'] = received_with.strip()
  534. notes = x.get('notes')
  535. if notes is not None:
  536. notes = notes.strip()
  537. if notes:
  538. award['notes'] = notes
  539. award['anchor'] = x.get('anchor')
  540. return award
  541. class DOMHTMLAwardsParser(DOMParserBase):
  542. """Parser for the "awards" page of a given person or movie.
  543. The page should be provided as a string, as taken from
  544. the akas.imdb.com server. The final result will be a
  545. dictionary, with a key for every relevant section.
  546. Example:
  547. awparser = HTMLAwardsParser()
  548. result = awparser.parse(awards_html_string)
  549. """
  550. subject = 'title'
  551. _containsObjects = True
  552. extractors = [
  553. Extractor(label='awards',
  554. group="//table//big",
  555. group_key="./a",
  556. path="./ancestor::tr[1]/following-sibling::tr/" \
  557. "td[last()][not(@colspan)]",
  558. attrs=Attribute(key=None,
  559. multi=True,
  560. path={
  561. 'year': "../td[1]/a/text()",
  562. 'result': "../td[2]/b/text()",
  563. 'award': "../td[3]/text()",
  564. 'category': "./text()[1]",
  565. # FIXME: takes only the first co-recipient
  566. 'with': "./small[starts-with(text()," \
  567. " 'Shared with:')]/following-sibling::a[1]/text()",
  568. 'notes': "./small[last()]//text()",
  569. 'anchor': ".//text()"
  570. },
  571. postprocess=_process_award
  572. )),
  573. Extractor(label='recipients',
  574. group="//table//big",
  575. group_key="./a",
  576. path="./ancestor::tr[1]/following-sibling::tr/" \
  577. "td[last()]/small[1]/preceding-sibling::a",
  578. attrs=Attribute(key=None,
  579. multi=True,
  580. path={
  581. 'name': "./text()",
  582. 'link': "./@href",
  583. 'anchor': "..//text()"
  584. }
  585. ))
  586. ]
  587. preprocessors = [
  588. (re.compile('(<tr><td[^>]*>.*?</td></tr>\n\n</table>)', re.I),
  589. r'\1</table>'),
  590. (re.compile('(<tr><td[^>]*>\n\n<big>.*?</big></td></tr>)', re.I),
  591. r'</table><table class="_imdbpy">\1'),
  592. (re.compile('(<table[^>]*>\n\n)</table>(<table)', re.I), r'\1\2'),
  593. (re.compile('(<small>.*?)<br>(.*?</small)', re.I), r'\1 \2'),
  594. (re.compile('(</tr>\n\n)(<td)', re.I), r'\1<tr>\2')
  595. ]
  596. def preprocess_dom(self, dom):
  597. """Repeat td elements according to their rowspan attributes
  598. in subsequent tr elements.
  599. """
  600. cols = self.xpath(dom, "//td[@rowspan]")
  601. for col in cols:
  602. span = int(col.get('rowspan'))
  603. del col.attrib['rowspan']
  604. position = len(self.xpath(col, "./preceding-sibling::td"))
  605. row = col.getparent()
  606. for tr in self.xpath(row, "./following-sibling::tr")[:span-1]:
  607. # if not cloned, child will be moved to new parent
  608. clone = self.clone(col)
  609. # XXX: beware that here we don't use an "adapted" function,
  610. # because both BeautifulSoup and lxml uses the same
  611. # "insert" method.
  612. tr.insert(position, clone)
  613. return dom
  614. def postprocess_data(self, data):
  615. if len(data) == 0:
  616. return {}
  617. nd = []
  618. for key in data.keys():
  619. dom = self.get_dom(key)
  620. assigner = self.xpath(dom, "//a/text()")[0]
  621. for entry in data[key]:
  622. if not entry.has_key('name'):
  623. if not entry:
  624. continue
  625. # this is an award, not a recipient
  626. entry['assigner'] = assigner.strip()
  627. # find the recipients
  628. matches = [p for p in data[key]
  629. if p.has_key('name') and (entry['anchor'] ==
  630. p['anchor'])]
  631. if self.subject == 'title':
  632. recipients = [Person(name=recipient['name'],
  633. personID=analyze_imdbid(recipient['link']))
  634. for recipient in matches]
  635. entry['to'] = recipients
  636. elif self.subject == 'name':
  637. recipients = [Movie(title=recipient['name'],
  638. movieID=analyze_imdbid(recipient['link']))
  639. for recipient in matches]
  640. entry['for'] = recipients
  641. nd.append(entry)
  642. del entry['anchor']
  643. return {'awards': nd}
  644. class DOMHTMLTaglinesParser(DOMParserBase):
  645. """Parser for the "taglines" page of a given movie.
  646. The page should be provided as a string, as taken from
  647. the akas.imdb.com server. The final result will be a
  648. dictionary, with a key for every relevant section.
  649. Example:
  650. tparser = DOMHTMLTaglinesParser()
  651. result = tparser.parse(taglines_html_string)
  652. """
  653. extractors = [Extractor(label='taglines',
  654. path='//*[contains(concat(" ", normalize-space(@class), " "), " soda ")]',
  655. attrs=Attribute(key='taglines',
  656. multi=True,
  657. path="./text()"))]
  658. def postprocess_data(self, data):
  659. if 'taglines' in data:
  660. data['taglines'] = [tagline.strip() for tagline in data['taglines']]
  661. return data
  662. class DOMHTMLKeywordsParser(DOMParserBase):
  663. """Parser for the "keywords" page of a given movie.
  664. The page should be provided as a string, as taken from
  665. the akas.imdb.com server. The final result will be a
  666. dictionary, with a key for every relevant section.
  667. Example:
  668. kwparser = DOMHTMLKeywordsParser()
  669. result = kwparser.parse(keywords_html_string)
  670. """
  671. extractors = [Extractor(label='keywords',
  672. path="//a[starts-with(@href, '/keyword/')]",
  673. attrs=Attribute(key='keywords',
  674. path="./text()", multi=True,
  675. postprocess=lambda x: \
  676. x.lower().replace(' ', '-')))]
  677. class DOMHTMLAlternateVersionsParser(DOMParserBase):
  678. """Parser for the "alternate versions" page of a given movie.
  679. The page should be provided as a string, as taken from
  680. the akas.imdb.com server. The final result will be a
  681. dictionary, with a key for every relevant section.
  682. Example:
  683. avparser = HTMLAlternateVersionsParser()
  684. result = avparser.parse(alternateversions_html_string)
  685. """
  686. _defGetRefs = True
  687. extractors = [Extractor(label='alternate versions',
  688. path="//ul[@class='trivia']/li",
  689. attrs=Attribute(key='alternate versions',
  690. multi=True,
  691. path=".//text()",
  692. postprocess=lambda x: x.strip()))]
  693. class DOMHTMLTriviaParser(DOMParserBase):
  694. """Parser for the "trivia" page of a given movie.
  695. The page should be provided as a string, as taken from
  696. the akas.imdb.com server. The final result will be a
  697. dictionary, with a key for every relevant section.
  698. Example:
  699. avparser = HTMLAlternateVersionsParser()
  700. result = avparser.parse(alternateversions_html_string)
  701. """
  702. _defGetRefs = True
  703. extractors = [Extractor(label='alternate versions',
  704. path="//div[@class='sodatext']",
  705. attrs=Attribute(key='trivia',
  706. multi=True,
  707. path=".//text()",
  708. postprocess=lambda x: x.strip()))]
  709. def preprocess_dom(self, dom):
  710. # Remove "link this quote" links.
  711. for qLink in self.xpath(dom, "//span[@class='linksoda']"):
  712. qLink.drop_tree()
  713. return dom
  714. class DOMHTMLSoundtrackParser(DOMHTMLAlternateVersionsParser):
  715. kind = 'soundtrack'
  716. preprocessors = [
  717. ('<br>', '\n')
  718. ]
  719. def postprocess_data(self, data):
  720. if 'alternate versions' in data:
  721. nd = []
  722. for x in data['alternate versions']:
  723. ds = x.split('\n')
  724. title = ds[0]
  725. if title[0] == '"' and title[-1] == '"':
  726. title = title[1:-1]
  727. nds = []
  728. newData = {}
  729. for l in ds[1:]:
  730. if ' with ' in l or ' by ' in l or ' from ' in l \
  731. or ' of ' in l or l.startswith('From '):
  732. nds.append(l)
  733. else:
  734. if nds:
  735. nds[-1] += l
  736. else:
  737. nds.append(l)
  738. newData[title] = {}
  739. for l in nds:
  740. skip = False
  741. for sep in ('From ',):
  742. if l.startswith(sep):
  743. fdix = len(sep)
  744. kind = l[:fdix].rstrip().lower()
  745. info = l[fdix:].lstrip()
  746. newData[title][kind] = info
  747. skip = True
  748. if not skip:
  749. for sep in ' with ', ' by ', ' from ', ' of ':
  750. fdix = l.find(sep)
  751. if fdix != -1:
  752. fdix = fdix+len(sep)
  753. kind = l[:fdix].rstrip().lower()
  754. info = l[fdix:].lstrip()
  755. newData[title][kind] = info
  756. break
  757. nd.append(newData)
  758. data['soundtrack'] = nd
  759. return data
  760. class DOMHTMLCrazyCreditsParser(DOMParserBase):
  761. """Parser for the "crazy credits" page of a given movie.
  762. The page should be provided as a string, as taken from
  763. the akas.imdb.com server. The final result will be a
  764. dictionary, with a key for every relevant section.
  765. Example:
  766. ccparser = DOMHTMLCrazyCreditsParser()
  767. result = ccparser.parse(crazycredits_html_string)
  768. """
  769. _defGetRefs = True
  770. extractors = [Extractor(label='crazy credits', path="//ul/li/tt",
  771. attrs=Attribute(key='crazy credits', multi=True,
  772. path=".//text()",
  773. postprocess=lambda x: \
  774. x.replace('\n', ' ').replace(' ', ' ')))]
  775. def _process_goof(x):
  776. if x['spoiler_category']:
  777. return x['spoiler_category'].strip() + ': SPOILER: ' + x['text'].strip()
  778. else:
  779. return x['category'].strip() + ': ' + x['text'].strip()
  780. class DOMHTMLGoofsParser(DOMParserBase):
  781. """Parser for the "goofs" page of a given movie.
  782. The page should be provided as a string, as taken from
  783. the akas.imdb.com server. The final result will be a
  784. dictionary, with a key for every relevant section.
  785. Example:
  786. gparser = DOMHTMLGoofsParser()
  787. result = gparser.parse(goofs_html_string)
  788. """
  789. _defGetRefs = True
  790. extractors = [Extractor(label='goofs', path="//div[@class='soda odd']",
  791. attrs=Attribute(key='goofs', multi=True,
  792. path={
  793. 'text':"./text()",
  794. 'category':'./preceding-sibling::h4[1]/text()',
  795. 'spoiler_category': './h4/text()'
  796. },
  797. postprocess=_process_goof))]
  798. class DOMHTMLQuotesParser(DOMParserBase):
  799. """Parser for the "memorable quotes" page of a given movie.
  800. The page should be provided as a string, as taken from
  801. the akas.imdb.com server. The final result will be a
  802. dictionary, with a key for every relevant section.
  803. Example:
  804. qparser = DOMHTMLQuotesParser()
  805. result = qparser.parse(quotes_html_string)
  806. """
  807. _defGetRefs = True
  808. extractors = [
  809. Extractor(label='quotes_odd',
  810. path="//div[@class='quote soda odd']",
  811. attrs=Attribute(key='quotes_odd',
  812. multi=True,
  813. path=".//text()",
  814. postprocess=lambda x: x.strip().replace(' \n',
  815. '::').replace('::\n', '::').replace('\n', ' '))),
  816. Extractor(label='quotes_even',
  817. path="//div[@class='quote soda even']",
  818. attrs=Attribute(key='quotes_even',
  819. multi=True,
  820. path=".//text()",
  821. postprocess=lambda x: x.strip().replace(' \n',
  822. '::').replace('::\n', '::').replace('\n', ' ')))
  823. ]
  824. preprocessors = [
  825. (re.compile('<a href="#" class="hidesoda hidden">Hide options</a><br>', re.I), '')
  826. ]
  827. def preprocess_dom(self, dom):
  828. # Remove "link this quote" links.
  829. for qLink in self.xpath(dom, "//span[@class='linksoda']"):
  830. qLink.drop_tree()
  831. for qLink in self.xpath(dom, "//div[@class='sharesoda_pre']"):
  832. qLink.drop_tree()
  833. return dom
  834. def postprocess_data(self, data):
  835. quotes = data.get('quotes_odd', []) + data.get('quotes_even', [])
  836. if not quotes:
  837. return {}
  838. quotes = [q.split('::') for q in quotes]
  839. return {'quotes': quotes}
  840. class DOMHTMLReleaseinfoParser(DOMParserBase):
  841. """Parser for the "release dates" page of a given movie.
  842. The page should be provided as a string, as taken from
  843. the akas.imdb.com server. The final result will be a
  844. dictionary, with a key for every relevant section.
  845. Example:
  846. rdparser = DOMHTMLReleaseinfoParser()
  847. result = rdparser.parse(releaseinfo_html_string)
  848. """
  849. extractors = [Extractor(label='release dates',
  850. path="//table[@id='release_dates']//tr",
  851. attrs=Attribute(key='release dates', multi=True,
  852. path={'country': ".//td[1]//text()",
  853. 'date': ".//td[2]//text()",
  854. 'notes': ".//td[3]//text()"})),
  855. Extractor(label='akas',
  856. path="//table[@id='akas']//tr",
  857. attrs=Attribute(key='akas', multi=True,
  858. path={'title': "./td[1]/text()",
  859. 'countries': "./td[2]/text()"}))]
  860. preprocessors = [
  861. (re.compile('(<h5><a name="?akas"?.*</table>)', re.I | re.M | re.S),
  862. r'<div class="_imdbpy_akas">\1</div>')]
  863. def postprocess_data(self, data):
  864. if not ('release dates' in data or 'akas' in data): return data
  865. releases = data.get('release dates') or []
  866. rl = []
  867. for i in releases:
  868. country = i.get('country')
  869. date = i.get('date')
  870. if not (country and date): continue
  871. country = country.strip()
  872. date = date.strip()
  873. if not (country and date): continue
  874. notes = i['notes']
  875. info = u'%s::%s' % (country, date)
  876. if notes:
  877. info += notes
  878. rl.append(info)
  879. if releases:
  880. del data['release dates']
  881. if rl:
  882. data['release dates'] = rl
  883. akas = data.get('akas') or []
  884. nakas = []
  885. for aka in akas:
  886. title = (aka.get('title') or '').strip()
  887. if not title:
  888. continue
  889. countries = (aka.get('countries') or '').split(',')
  890. if not countries:
  891. nakas.append(title)
  892. else:
  893. for country in countries:
  894. nakas.append('%s::%s' % (title, country.strip()))
  895. if akas:
  896. del data['akas']
  897. if nakas:
  898. data['akas from release info'] = nakas
  899. return data
  900. class DOMHTMLRatingsParser(DOMParserBase):
  901. """Parser for the "user ratings" page of a given movie.
  902. The page should be provided as a string, as taken from
  903. the akas.imdb.com server. The final result will be a
  904. dictionary, with a key for every relevant section.
  905. Example:
  906. rparser = DOMHTMLRatingsParser()
  907. result = rparser.parse(userratings_html_string)
  908. """
  909. re_means = re.compile('mean\s*=\s*([0-9]\.[0-9])\.\s*median\s*=\s*([0-9])',
  910. re.I)
  911. extractors = [
  912. Extractor(label='number of votes',
  913. path="//td[b='Percentage']/../../tr",
  914. attrs=[Attribute(key='votes',
  915. multi=True,
  916. path={
  917. 'votes': "td[1]//text()",
  918. 'ordinal': "td[3]//text()"
  919. })]),
  920. Extractor(label='mean and median',
  921. path="//p[starts-with(text(), 'Arithmetic mean')]",
  922. attrs=Attribute(key='mean and median',
  923. path="text()")),
  924. Extractor(label='rating',
  925. path="//a[starts-with(@href, '/search/title?user_rating=')]",
  926. attrs=Attribute(key='rating',
  927. path="text()")),
  928. Extractor(label='demographic voters',
  929. path="//td[b='Average']/../../tr",
  930. attrs=Attribute(key='demographic voters',
  931. multi=True,
  932. path={
  933. 'voters': "td[1]//text()",
  934. 'votes': "td[2]//text()",
  935. 'average': "td[3]//text()"
  936. })),
  937. Extractor(label='top 250',
  938. path="//a[text()='top 250']",
  939. attrs=Attribute(key='top 250',
  940. path="./preceding-sibling::text()[1]"))
  941. ]
  942. def postprocess_data(self, data):
  943. nd = {}
  944. votes = data.get('votes', [])
  945. if votes:
  946. nd['number of votes'] = {}
  947. for i in xrange(1, 11):
  948. _ordinal = int(votes[i]['ordinal'])
  949. _strvts = votes[i]['votes'] or '0'
  950. nd['number of votes'][_ordinal] = \
  951. int(_strvts.replace(',', ''))
  952. mean = data.get('mean and median', '')
  953. if mean:
  954. means = self.re_means.findall(mean)
  955. if means and len(means[0]) == 2:
  956. am, med = means[0]
  957. try: am = float(am)
  958. except (ValueError, OverflowError): pass
  959. if type(am) is type(1.0):
  960. nd['arithmetic mean'] = am
  961. try: med = int(med)
  962. except (ValueError, OverflowError): pass
  963. if type(med) is type(0):
  964. nd['median'] = med
  965. if 'rating' in data:
  966. nd['rating'] = float(data['rating'])
  967. dem_voters = data.get('demographic voters')
  968. if dem_voters:
  969. nd['demographic'] = {}
  970. for i in xrange(1, len(dem_voters)):
  971. if (dem_voters[i]['votes'] is not None) \
  972. and (dem_voters[i]['votes'].strip()):
  973. nd['demographic'][dem_voters[i]['voters'].strip().lower()] \
  974. = (int(dem_voters[i]['votes'].replace(',', '')),
  975. float(dem_voters[i]['average']))
  976. if 'imdb users' in nd.get('demographic', {}):
  977. nd['votes'] = nd['demographic']['imdb users'][0]
  978. nd['demographic']['all votes'] = nd['demographic']['imdb users']
  979. del nd['demographic']['imdb users']
  980. top250 = data.get('top 250')
  981. if top250:
  982. sd = top250[9:]
  983. i = sd.find(' ')
  984. if i != -1:
  985. sd = sd[:i]
  986. try: sd = int(sd)
  987. except (ValueError, OverflowError): pass
  988. if type(sd) is type(0):
  989. nd['top 250 rank'] = sd
  990. return nd
  991. class DOMHTMLEpisodesRatings(DOMParserBase):
  992. """Parser for the "episode ratings ... by date" page of a given movie.
  993. The page should be provided as a string, as taken from
  994. the akas.imdb.com server. The final result will be a
  995. dictionary, with a key for every relevant section.
  996. Example:
  997. erparser = DOMHTMLEpisodesRatings()
  998. result = erparser.parse(eprating_html_string)
  999. """
  1000. _containsObjects = True
  1001. extractors = [Extractor(label='title', path="//title",
  1002. attrs=Attribute(key='title', path="./text()")),
  1003. Extractor(label='ep ratings',
  1004. path="//th/../..//tr",
  1005. attrs=Attribute(key='episodes', multi=True,
  1006. path={'nr': ".//td[1]/text()",
  1007. 'ep title': ".//td[2]//text()",
  1008. 'movieID': ".//td[2]/a/@href",
  1009. 'rating': ".//td[3]/text()",
  1010. 'votes': ".//td[4]/text()"}))]
  1011. def postprocess_data(self, data):
  1012. if 'title' not in data or 'episodes' not in data: return {}
  1013. nd = []
  1014. title = data['title']
  1015. for i in data['episodes']:
  1016. ept = i['ep title']
  1017. movieID = analyze_imdbid(i['movieID'])
  1018. votes = i['votes']
  1019. rating = i['rating']
  1020. if not (ept and movieID and votes and rating): continue
  1021. try:
  1022. votes = int(votes.replace(',', '').replace('.', ''))
  1023. except:
  1024. pass
  1025. try:
  1026. rating = float(rating)
  1027. except:
  1028. pass
  1029. ept = ept.strip()
  1030. ept = u'%s {%s' % (title, ept)
  1031. nr = i['nr']
  1032. if nr:
  1033. ept += u' (#%s)' % nr.strip()
  1034. ept += '}'
  1035. if movieID is not None:
  1036. movieID = str(movieID)
  1037. m = Movie(title=ept, movieID=movieID, accessSystem=self._as,
  1038. modFunct=self._modFunct)
  1039. epofdict = m.get('episode of')
  1040. if epofdict is not None:
  1041. m['episode of'] = Movie(data=epofdict, accessSystem=self._as,
  1042. modFunct=self._modFunct)
  1043. nd.append({'episode': m, 'votes': votes, 'rating': rating})
  1044. return {'episodes rating': nd}
  1045. def _normalize_href(href):
  1046. if (href is not None) and (not href.lower().startswith('http://')):
  1047. if href.startswith('/'): href = href[1:]
  1048. # TODO: imdbURL_base may be set by the user!
  1049. href = '%s%s' % (imdbURL_base, href)
  1050. return href
  1051. class DOMHTMLCriticReviewsParser(DOMParserBase):
  1052. """Parser for the "critic reviews" pages of a given movie.
  1053. The page should be provided as a string, as taken from
  1054. the akas.imdb.com server. The final result will be a
  1055. dictionary, with a key for every releva

Large files files are truncated, but you can click here to view the full file