PageRenderTime 56ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/dependencies/imdbpy/imdb/parser/http/movieParser.py

https://bitbucket.org/filmaster/filmaster-stable/
Python | 1923 lines | 1884 code | 13 blank | 26 comment | 23 complexity | 5dc80d4409a77ef3c03496d0d983b3aa MD5 | raw file
Possible License(s): BSD-2-Clause, GPL-2.0, BSD-3-Clause, JSON

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-2010 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. """Return a splitter function suitable for a given set of data."""
  112. def splitter(x):
  113. if not x: return x
  114. x = x.strip()
  115. if not x: return x
  116. if lstrip is not None:
  117. x = x.lstrip(lstrip).lstrip()
  118. lx = x.split(sep)
  119. lx[:] = filter(None, [j.strip() for j in lx])
  120. if comments:
  121. lx[:] = [j.replace(' (', '::(', 1) for j in lx]
  122. return lx
  123. return splitter
  124. def _toInt(val, replace=()):
  125. """Return the value, converted to integer, or None; if present, 'replace'
  126. must be a list of tuples of values to replace."""
  127. for before, after in replace:
  128. val = val.replace(before, after)
  129. try:
  130. return int(val)
  131. except (TypeError, ValueError):
  132. return None
  133. class DOMHTMLMovieParser(DOMParserBase):
  134. """Parser for the "combined details" (and if instance.mdparse is
  135. True also for the "main details") page of a given movie.
  136. The page should be provided as a string, as taken from
  137. the akas.imdb.com server. The final result will be a
  138. dictionary, with a key for every relevant section.
  139. Example:
  140. mparser = DOMHTMLMovieParser()
  141. result = mparser.parse(combined_details_html_string)
  142. """
  143. _containsObjects = True
  144. extractors = [Extractor(label='title',
  145. path="//h1",
  146. attrs=Attribute(key='title',
  147. path=".//text()",
  148. postprocess=analyze_title)),
  149. Extractor(label='glossarysections',
  150. group="//a[@class='glossary']",
  151. group_key="./@name",
  152. group_key_normalize=lambda x: x.replace('_', ' '),
  153. path="../../../..//tr",
  154. attrs=Attribute(key=None,
  155. multi=True,
  156. path={'person': ".//text()",
  157. 'link': "./td[1]/a[@href]/@href"},
  158. postprocess=lambda x: \
  159. build_person(x.get('person') or u'',
  160. personID=analyze_imdbid(x.get('link')))
  161. )),
  162. Extractor(label='cast',
  163. path="//table[@class='cast']//tr",
  164. attrs=Attribute(key="cast",
  165. multi=True,
  166. path={'person': ".//text()",
  167. 'link': "td[2]/a/@href",
  168. 'roleID': \
  169. "td[4]/div[@class='_imdbpyrole']/@roleid"},
  170. postprocess=lambda x: \
  171. build_person(x.get('person') or u'',
  172. personID=analyze_imdbid(x.get('link')),
  173. roleID=(x.get('roleID') or u'').split('/'))
  174. )),
  175. Extractor(label='genres',
  176. path="//div[@class='info']//a[starts-with(@href," \
  177. " '/Sections/Genres')]",
  178. attrs=Attribute(key="genres",
  179. multi=True,
  180. path="./text()")),
  181. Extractor(label='h5sections',
  182. path="//div[@class='info']/h5/..",
  183. attrs=[
  184. Attribute(key="plot summary",
  185. path="./h5[starts-with(text(), " \
  186. "'Plot:')]/../div/text()",
  187. postprocess=lambda x: \
  188. x.strip().rstrip('|').rstrip()),
  189. Attribute(key="aspect ratio",
  190. path="./h5[starts-with(text()," \
  191. " 'Aspect')]/../div/text()",
  192. postprocess=lambda x: x.strip()),
  193. Attribute(key="mpaa",
  194. path="./h5/a[starts-with(text()," \
  195. " 'MPAA')]/../../div/text()",
  196. postprocess=lambda x: x.strip()),
  197. #fix by Pawel Maczewski (email)
  198. Attribute(key="countries",
  199. path="./h5[starts-with(text(), " \
  200. "'Countr')]/..//a/text()",
  201. postprocess=makeSplitter(sep='|')),
  202. # postprocess=makeSplitter(sep='\n')),
  203. Attribute(key="language",
  204. path="./h5[starts-with(text(), " \
  205. "'Language')]/..//text()",
  206. postprocess=makeSplitter('Language:')),
  207. Attribute(key='color info',
  208. path="./h5[starts-with(text(), " \
  209. "'Color')]/..//text()",
  210. postprocess=makeSplitter('Color:')),
  211. Attribute(key='sound mix',
  212. path="./h5[starts-with(text(), " \
  213. "'Sound Mix')]/..//text()",
  214. postprocess=makeSplitter('Sound Mix:')),
  215. # Collects akas not encosed in <i> tags.
  216. Attribute(key='other akas',
  217. path="./h5[starts-with(text(), " \
  218. "'Also Known As')]/../div//text()",
  219. postprocess=makeSplitter(sep='::')),
  220. Attribute(key='runtimes',
  221. path="./h5[starts-with(text(), " \
  222. "'Runtime')]/../div/text()",
  223. postprocess=makeSplitter()),
  224. Attribute(key='certificates',
  225. path="./h5[starts-with(text(), " \
  226. "'Certificat')]/..//text()",
  227. postprocess=makeSplitter('Certification:')),
  228. Attribute(key='number of seasons',
  229. path="./h5[starts-with(text(), " \
  230. "'Seasons')]/..//text()",
  231. postprocess=lambda x: x.count('|') + 1),
  232. Attribute(key='original air date',
  233. path="./h5[starts-with(text(), " \
  234. "'Original Air Date')]/../div/text()"),
  235. Attribute(key='tv series link',
  236. path="./h5[starts-with(text(), " \
  237. "'TV Series')]/..//a/@href"),
  238. Attribute(key='tv series title',
  239. path="./h5[starts-with(text(), " \
  240. "'TV Series')]/..//a/text()")
  241. ]),
  242. Extractor(label='creator',
  243. path="//h5[starts-with(text(), 'Creator')]/..//a",
  244. attrs=Attribute(key='creator', multi=True,
  245. path={'name': "./text()",
  246. 'link': "./@href"},
  247. postprocess=lambda x: \
  248. build_person(x.get('name') or u'',
  249. personID=analyze_imdbid(x.get('link')))
  250. )),
  251. Extractor(label='thin writer',
  252. path="//h5[starts-with(text(), 'Writer')]/..//a",
  253. attrs=Attribute(key='thin writer', multi=True,
  254. path={'name': "./text()",
  255. 'link': "./@href"},
  256. postprocess=lambda x: \
  257. build_person(x.get('name') or u'',
  258. personID=analyze_imdbid(x.get('link')))
  259. )),
  260. Extractor(label='thin director',
  261. path="//h5[starts-with(text(), 'Director')]/..//a",
  262. attrs=Attribute(key='thin director', multi=True,
  263. path={'name': "./text()",
  264. 'link': "@href"},
  265. postprocess=lambda x: \
  266. build_person(x.get('name') or u'',
  267. personID=analyze_imdbid(x.get('link')))
  268. )),
  269. Extractor(label='top 250/bottom 100',
  270. path="//div[@class='starbar-special']/" \
  271. "a[starts-with(@href, '/chart/')]",
  272. attrs=Attribute(key='top/bottom rank',
  273. path="./text()")),
  274. Extractor(label='series years',
  275. path="//div[@id='tn15title']//span" \
  276. "[starts-with(text(), 'TV series')]",
  277. attrs=Attribute(key='series years',
  278. path="./text()",
  279. postprocess=lambda x: \
  280. x.replace('TV series','').strip())),
  281. Extractor(label='number of episodes',
  282. path="//a[@title='Full Episode List']",
  283. attrs=Attribute(key='number of episodes',
  284. path="./text()",
  285. postprocess=lambda x: \
  286. _toInt(x, [(' Episodes', '')]))),
  287. Extractor(label='akas',
  288. path="//i[@class='transl']",
  289. attrs=Attribute(key='akas', multi=True, path='text()',
  290. postprocess=lambda x:
  291. x.replace(' ', ' ').replace(' (',
  292. '::(', 1).replace(' ', ' '))),
  293. Extractor(label='production notes/status',
  294. path="//div[@class='info inprod']",
  295. attrs=Attribute(key='production notes',
  296. path=".//text()",
  297. postprocess=lambda x: x.strip())),
  298. Extractor(label='blackcatheader',
  299. group="//b[@class='blackcatheader']",
  300. group_key="./text()",
  301. group_key_normalize=lambda x: x.lower(),
  302. path="../ul/li",
  303. attrs=Attribute(key=None,
  304. multi=True,
  305. path={'name': "./a//text()",
  306. 'comp-link': "./a/@href",
  307. 'notes': "./text()"},
  308. postprocess=lambda x: \
  309. Company(name=x.get('name') or u'',
  310. companyID=analyze_imdbid(x.get('comp-link')),
  311. notes=(x.get('notes') or u'').strip())
  312. )),
  313. Extractor(label='rating',
  314. path="//div[@class='starbar-meta']/b",
  315. attrs=Attribute(key='rating',
  316. path=".//text()")),
  317. Extractor(label='votes',
  318. path="//div[@class='starbar-meta']/a[@href]",
  319. attrs=Attribute(key='votes',
  320. path=".//text()")),
  321. Extractor(label='cover url',
  322. path="//a[@name='poster']",
  323. attrs=Attribute(key='cover url',
  324. path="./img/@src"))
  325. ]
  326. preprocessors = [
  327. (re.compile(r'(<b class="blackcatheader">.+?</b>)', re.I),
  328. r'</div><div>\1'),
  329. ('<small>Full cast and crew for<br></small>', ''),
  330. ('<td> </td>', '<td>...</td>'),
  331. ('<span class="tv-extra">TV mini-series</span>',
  332. '<span class="tv-extra">(mini)</span>'),
  333. (_reRolesMovie, _manageRoles),
  334. (_reAkas, _replaceBR)]
  335. def preprocess_dom(self, dom):
  336. # Handle series information.
  337. xpath = self.xpath(dom, "//b[text()='Series Crew']")
  338. if xpath:
  339. b = xpath[-1] # In doubt, take the last one.
  340. for a in self.xpath(b, "./following::h5/a[@class='glossary']"):
  341. name = a.get('name')
  342. if name:
  343. a.set('name', 'series %s' % name)
  344. # Remove links to IMDbPro.
  345. for proLink in self.xpath(dom, "//span[@class='pro-link']"):
  346. proLink.drop_tree()
  347. # Remove some 'more' links (keep others, like the one around
  348. # the number of votes).
  349. for tn15more in self.xpath(dom,
  350. "//a[@class='tn15more'][starts-with(@href, '/title/')]"):
  351. tn15more.drop_tree()
  352. return dom
  353. re_space = re.compile(r'\s+')
  354. re_airdate = re.compile(r'(.*)\s*\(season (\d+), episode (\d+)\)', re.I)
  355. def postprocess_data(self, data):
  356. # Convert section names.
  357. for sect in data.keys():
  358. if sect in _SECT_CONV:
  359. data[_SECT_CONV[sect]] = data[sect]
  360. del data[sect]
  361. sect = _SECT_CONV[sect]
  362. # Filter out fake values.
  363. for key in data:
  364. value = data[key]
  365. if isinstance(value, list) and value:
  366. if isinstance(value[0], Person):
  367. data[key] = filter(lambda x: x.personID is not None, value)
  368. if isinstance(value[0], _Container):
  369. for obj in data[key]:
  370. obj.accessSystem = self._as
  371. obj.modFunct = self._modFunct
  372. if 'akas' in data or 'other akas' in data:
  373. akas = data.get('akas') or []
  374. akas += data.get('other akas') or []
  375. if 'akas' in data:
  376. del data['akas']
  377. if 'other akas' in data:
  378. del data['other akas']
  379. if akas:
  380. data['akas'] = akas
  381. if 'runtimes' in data:
  382. data['runtimes'] = [x.replace(' min', u'')
  383. for x in data['runtimes']]
  384. if 'production notes' in data:
  385. pn = data['production notes'].replace('\n\nComments:',
  386. '\nComments:').replace('\n\nNote:',
  387. '\nNote:').replace('Note:\n\n',
  388. 'Note:\n').split('\n')
  389. for k, v in zip(pn[::2], pn[1::2]):
  390. v = v.strip()
  391. if not v:
  392. continue
  393. k = k.lower().strip(':')
  394. if k == 'note':
  395. k = 'status note'
  396. data[k] = v
  397. del data['production notes']
  398. if 'original air date' in data:
  399. oid = self.re_space.sub(' ', data['original air date']).strip()
  400. data['original air date'] = oid
  401. aid = self.re_airdate.findall(oid)
  402. if aid and len(aid[0]) == 3:
  403. date, season, episode = aid[0]
  404. date = date.strip()
  405. try: season = int(season)
  406. except: pass
  407. try: episode = int(episode)
  408. except: pass
  409. if date and date != '????':
  410. data['original air date'] = date
  411. else:
  412. del data['original air date']
  413. # Handle also "episode 0".
  414. if season or type(season) is type(0):
  415. data['season'] = season
  416. if episode or type(season) is type(0):
  417. data['episode'] = episode
  418. for k in ('writer', 'director'):
  419. t_k = 'thin %s' % k
  420. if t_k not in data:
  421. continue
  422. if k not in data:
  423. data[k] = data[t_k]
  424. del data[t_k]
  425. if 'top/bottom rank' in data:
  426. tbVal = data['top/bottom rank'].lower()
  427. if tbVal.startswith('top'):
  428. tbKey = 'top 250 rank'
  429. tbVal = _toInt(tbVal, [('top 250: #', '')])
  430. else:
  431. tbKey = 'bottom 100 rank'
  432. tbVal = _toInt(tbVal, [('bottom 100: #', '')])
  433. if tbVal:
  434. data[tbKey] = tbVal
  435. del data['top/bottom rank']
  436. if 'year' in data and data['year'] == '????':
  437. del data['year']
  438. if 'tv series link' in data:
  439. if 'tv series title' in data:
  440. data['episode of'] = Movie(title=data['tv series title'],
  441. movieID=analyze_imdbid(
  442. data['tv series link']),
  443. accessSystem=self._as,
  444. modFunct=self._modFunct)
  445. del data['tv series title']
  446. del data['tv series link']
  447. if 'rating' in data:
  448. try:
  449. data['rating'] = float(data['rating'].replace('/10', ''))
  450. except (TypeError, ValueError):
  451. pass
  452. if 'votes' in data:
  453. try:
  454. votes = data['votes'].replace(',', '').replace('votes', '')
  455. data['votes'] = int(votes)
  456. except (TypeError, ValueError):
  457. pass
  458. return data
  459. def _process_plotsummary(x):
  460. """Process a plot (contributed by Rdian06)."""
  461. if x.get('author') is None:
  462. xauthor = u'Anonymous'
  463. else:
  464. xauthor = x.get('author').replace('{', '<').replace('}',
  465. '>').replace('(','<').replace(')', '>')
  466. xplot = x.get('plot', '').strip()
  467. return u'%s::%s' % (xplot, xauthor)
  468. class DOMHTMLPlotParser(DOMParserBase):
  469. """Parser for the "plot summary" page of a given movie.
  470. The page should be provided as a string, as taken from
  471. the akas.imdb.com server. The final result will be a
  472. dictionary, with a 'plot' key, containing a list
  473. of string with the structure: 'summary::summary_author <author@email>'.
  474. Example:
  475. pparser = HTMLPlotParser()
  476. result = pparser.parse(plot_summary_html_string)
  477. """
  478. _defGetRefs = True
  479. extractors = [Extractor(label='plot',
  480. path="//p[@class='plotpar']",
  481. attrs=Attribute(key='plot',
  482. multi=True,
  483. path={'plot': './text()',
  484. 'author': './i/a/text()'},
  485. postprocess=_process_plotsummary))]
  486. def _process_award(x):
  487. award = {}
  488. award['year'] = x.get('year').strip()
  489. if award['year'] and award['year'].isdigit():
  490. award['year'] = int(award['year'])
  491. award['result'] = x.get('result').strip()
  492. award['award'] = x.get('award').strip()
  493. category = x.get('category').strip()
  494. if category:
  495. award['category'] = category
  496. received_with = x.get('with')
  497. if received_with is not None:
  498. award['with'] = received_with.strip()
  499. notes = x.get('notes')
  500. if notes is not None:
  501. notes = notes.strip()
  502. if notes:
  503. award['notes'] = notes
  504. award['anchor'] = x.get('anchor')
  505. return award
  506. class DOMHTMLAwardsParser(DOMParserBase):
  507. """Parser for the "awards" page of a given person or movie.
  508. The page should be provided as a string, as taken from
  509. the akas.imdb.com server. The final result will be a
  510. dictionary, with a key for every relevant section.
  511. Example:
  512. awparser = HTMLAwardsParser()
  513. result = awparser.parse(awards_html_string)
  514. """
  515. subject = 'title'
  516. _containsObjects = True
  517. extractors = [
  518. Extractor(label='awards',
  519. group="//table//big",
  520. group_key="./a",
  521. path="./ancestor::tr[1]/following-sibling::tr/" \
  522. "td[last()][not(@colspan)]",
  523. attrs=Attribute(key=None,
  524. multi=True,
  525. path={
  526. 'year': "../td[1]/a/text()",
  527. 'result': "../td[2]/b/text()",
  528. 'award': "../td[3]/text()",
  529. 'category': "./text()[1]",
  530. # FIXME: takes only the first co-recipient
  531. 'with': "./small[starts-with(text()," \
  532. " 'Shared with:')]/following-sibling::a[1]/text()",
  533. 'notes': "./small[last()]//text()",
  534. 'anchor': ".//text()"
  535. },
  536. postprocess=_process_award
  537. )),
  538. Extractor(label='recipients',
  539. group="//table//big",
  540. group_key="./a",
  541. path="./ancestor::tr[1]/following-sibling::tr/" \
  542. "td[last()]/small[1]/preceding-sibling::a",
  543. attrs=Attribute(key=None,
  544. multi=True,
  545. path={
  546. 'name': "./text()",
  547. 'link': "./@href",
  548. 'anchor': "..//text()"
  549. }
  550. ))
  551. ]
  552. preprocessors = [
  553. (re.compile('(<tr><td[^>]*>.*?</td></tr>\n\n</table>)', re.I),
  554. r'\1</table>'),
  555. (re.compile('(<tr><td[^>]*>\n\n<big>.*?</big></td></tr>)', re.I),
  556. r'</table><table class="_imdbpy">\1'),
  557. (re.compile('(<table[^>]*>\n\n)</table>(<table)', re.I), r'\1\2'),
  558. (re.compile('(<small>.*?)<br>(.*?</small)', re.I), r'\1 \2'),
  559. (re.compile('(</tr>\n\n)(<td)', re.I), r'\1<tr>\2')
  560. ]
  561. def preprocess_dom(self, dom):
  562. """Repeat td elements according to their rowspan attributes
  563. in subsequent tr elements.
  564. """
  565. cols = self.xpath(dom, "//td[@rowspan]")
  566. for col in cols:
  567. span = int(col.get('rowspan'))
  568. del col.attrib['rowspan']
  569. position = len(self.xpath(col, "./preceding-sibling::td"))
  570. row = col.getparent()
  571. for tr in self.xpath(row, "./following-sibling::tr")[:span-1]:
  572. # if not cloned, child will be moved to new parent
  573. clone = self.clone(col)
  574. # XXX: beware that here we don't use an "adapted" function,
  575. # because both BeautifulSoup and lxml uses the same
  576. # "insert" method.
  577. tr.insert(position, clone)
  578. return dom
  579. def postprocess_data(self, data):
  580. if len(data) == 0:
  581. return {}
  582. nd = []
  583. for key in data.keys():
  584. dom = self.get_dom(key)
  585. assigner = self.xpath(dom, "//a/text()")[0]
  586. for entry in data[key]:
  587. if not entry.has_key('name'):
  588. # this is an award, not a recipient
  589. entry['assigner'] = assigner.strip()
  590. # find the recipients
  591. matches = [p for p in data[key]
  592. if p.has_key('name') and (entry['anchor'] ==
  593. p['anchor'])]
  594. if self.subject == 'title':
  595. recipients = [Person(name=recipient['name'],
  596. personID=analyze_imdbid(recipient['link']))
  597. for recipient in matches]
  598. entry['to'] = recipients
  599. elif self.subject == 'name':
  600. recipients = [Movie(title=recipient['name'],
  601. movieID=analyze_imdbid(recipient['link']))
  602. for recipient in matches]
  603. entry['for'] = recipients
  604. nd.append(entry)
  605. del entry['anchor']
  606. return {'awards': nd}
  607. class DOMHTMLTaglinesParser(DOMParserBase):
  608. """Parser for the "taglines" page of a given movie.
  609. The page should be provided as a string, as taken from
  610. the akas.imdb.com server. The final result will be a
  611. dictionary, with a key for every relevant section.
  612. Example:
  613. tparser = DOMHTMLTaglinesParser()
  614. result = tparser.parse(taglines_html_string)
  615. """
  616. extractors = [Extractor(label='taglines',
  617. path="//div[@id='tn15content']/p",
  618. attrs=Attribute(key='taglines', multi=True,
  619. path="./text()"))]
  620. class DOMHTMLKeywordsParser(DOMParserBase):
  621. """Parser for the "keywords" page of a given movie.
  622. The page should be provided as a string, as taken from
  623. the akas.imdb.com server. The final result will be a
  624. dictionary, with a key for every relevant section.
  625. Example:
  626. kwparser = DOMHTMLKeywordsParser()
  627. result = kwparser.parse(keywords_html_string)
  628. """
  629. extractors = [Extractor(label='keywords',
  630. path="//a[starts-with(@href, '/keyword/')]",
  631. attrs=Attribute(key='keywords',
  632. path="./text()", multi=True,
  633. postprocess=lambda x: \
  634. x.lower().replace(' ', '-')))]
  635. class DOMHTMLAlternateVersionsParser(DOMParserBase):
  636. """Parser for the "alternate versions" and "trivia" pages of a
  637. given movie.
  638. The page should be provided as a string, as taken from
  639. the akas.imdb.com server. The final result will be a
  640. dictionary, with a key for every relevant section.
  641. Example:
  642. avparser = HTMLAlternateVersionsParser()
  643. result = avparser.parse(alternateversions_html_string)
  644. """
  645. _defGetRefs = True
  646. kind = 'alternate versions'
  647. extractors = [Extractor(label='alternate versions',
  648. path="//ul[@class='trivia']/li",
  649. attrs=Attribute(key='self.kind',
  650. multi=True,
  651. path=".//text()",
  652. postprocess=lambda x: x.strip()))]
  653. class DOMHTMLSoundtrackParser(DOMHTMLAlternateVersionsParser):
  654. kind = 'soundtrack'
  655. preprocessors = [
  656. ('<br>', '\n')
  657. ]
  658. def postprocess_data(self, data):
  659. if 'soundtrack' in data:
  660. nd = []
  661. for x in data['soundtrack']:
  662. ds = x.split('\n')
  663. title = ds[0]
  664. if title[0] == '"' and title[-1] == '"':
  665. title = title[1:-1]
  666. nds = []
  667. newData = {}
  668. for l in ds[1:]:
  669. if ' with ' in l or ' by ' in l or ' from ' in l \
  670. or ' of ' in l or l.startswith('From '):
  671. nds.append(l)
  672. else:
  673. if nds:
  674. nds[-1] += l
  675. else:
  676. nds.append(l)
  677. newData[title] = {}
  678. for l in nds:
  679. skip = False
  680. for sep in ('From ',):
  681. if l.startswith(sep):
  682. fdix = len(sep)
  683. kind = l[:fdix].rstrip().lower()
  684. info = l[fdix:].lstrip()
  685. newData[title][kind] = info
  686. skip = True
  687. if not skip:
  688. for sep in ' with ', ' by ', ' from ', ' of ':
  689. fdix = l.find(sep)
  690. if fdix != -1:
  691. fdix = fdix+len(sep)
  692. kind = l[:fdix].rstrip().lower()
  693. info = l[fdix:].lstrip()
  694. newData[title][kind] = info
  695. break
  696. nd.append(newData)
  697. data['soundtrack'] = nd
  698. return data
  699. class DOMHTMLCrazyCreditsParser(DOMParserBase):
  700. """Parser for the "crazy credits" page of a given movie.
  701. The page should be provided as a string, as taken from
  702. the akas.imdb.com server. The final result will be a
  703. dictionary, with a key for every relevant section.
  704. Example:
  705. ccparser = DOMHTMLCrazyCreditsParser()
  706. result = ccparser.parse(crazycredits_html_string)
  707. """
  708. _defGetRefs = True
  709. extractors = [Extractor(label='crazy credits', path="//ul/li/tt",
  710. attrs=Attribute(key='crazy credits', multi=True,
  711. path=".//text()",
  712. postprocess=lambda x: \
  713. x.replace('\n', ' ').replace(' ', ' ')))]
  714. class DOMHTMLGoofsParser(DOMParserBase):
  715. """Parser for the "goofs" page of a given movie.
  716. The page should be provided as a string, as taken from
  717. the akas.imdb.com server. The final result will be a
  718. dictionary, with a key for every relevant section.
  719. Example:
  720. gparser = DOMHTMLGoofsParser()
  721. result = gparser.parse(goofs_html_string)
  722. """
  723. _defGetRefs = True
  724. extractors = [Extractor(label='goofs', path="//ul[@class='trivia']/li",
  725. attrs=Attribute(key='goofs', multi=True, path=".//text()",
  726. postprocess=lambda x: (x or u'').strip()))]
  727. class DOMHTMLQuotesParser(DOMParserBase):
  728. """Parser for the "memorable quotes" page of a given movie.
  729. The page should be provided as a string, as taken from
  730. the akas.imdb.com server. The final result will be a
  731. dictionary, with a key for every relevant section.
  732. Example:
  733. qparser = DOMHTMLQuotesParser()
  734. result = qparser.parse(quotes_html_string)
  735. """
  736. _defGetRefs = True
  737. extractors = [
  738. Extractor(label='quotes',
  739. path="//div[@class='_imdbpy']",
  740. attrs=Attribute(key='quotes',
  741. multi=True,
  742. path=".//text()",
  743. postprocess=lambda x: x.strip().replace(' \n',
  744. '::').replace('::\n', '::').replace('\n', ' ')))
  745. ]
  746. preprocessors = [
  747. (re.compile('(<a name="?qt[0-9]{7}"?></a>)', re.I),
  748. r'\1<div class="_imdbpy">'),
  749. (re.compile('<hr width="30%">', re.I), '</div>'),
  750. (re.compile('<hr/>', re.I), '</div>'),
  751. (re.compile('<script.*?</script>', re.I|re.S), ''),
  752. # For BeautifulSoup.
  753. (re.compile('<!-- sid: t-channel : MIDDLE_CENTER -->', re.I), '</div>')
  754. ]
  755. def preprocess_dom(self, dom):
  756. # Remove "link this quote" links.
  757. for qLink in self.xpath(dom, "//p[@class='linksoda']"):
  758. qLink.drop_tree()
  759. return dom
  760. def postprocess_data(self, data):
  761. if 'quotes' not in data:
  762. return {}
  763. for idx, quote in enumerate(data['quotes']):
  764. data['quotes'][idx] = quote.split('::')
  765. return data
  766. class DOMHTMLReleaseinfoParser(DOMParserBase):
  767. """Parser for the "release dates" page of a given movie.
  768. The page should be provided as a string, as taken from
  769. the akas.imdb.com server. The final result will be a
  770. dictionary, with a key for every relevant section.
  771. Example:
  772. rdparser = DOMHTMLReleaseinfoParser()
  773. result = rdparser.parse(releaseinfo_html_string)
  774. """
  775. extractors = [Extractor(label='release dates',
  776. path="//th[@class='xxxx']/../../tr",
  777. attrs=Attribute(key='release dates', multi=True,
  778. path={'country': ".//td[1]//text()",
  779. 'date': ".//td[2]//text()",
  780. 'notes': ".//td[3]//text()"})),
  781. Extractor(label='akas',
  782. path="//div[@class='_imdbpy_akas']/table/tr",
  783. attrs=Attribute(key='akas', multi=True,
  784. path={'title': "./td[1]/text()",
  785. 'countries': "./td[2]/text()"}))]
  786. preprocessors = [
  787. (re.compile('(<h5><a name="?akas"?.*</table>)', re.I | re.M | re.S),
  788. r'<div class="_imdbpy_akas">\1</div>')]
  789. def postprocess_data(self, data):
  790. if not ('release dates' in data or 'akas' in data): return data
  791. releases = data['release dates']
  792. rl = []
  793. for i in releases:
  794. country = i.get('country')
  795. date = i.get('date')
  796. if not (country and date): continue
  797. country = country.strip()
  798. date = date.strip()
  799. if not (country and date): continue
  800. notes = i['notes']
  801. info = u'%s::%s' % (country, date)
  802. if notes:
  803. info += notes
  804. rl.append(info)
  805. if releases:
  806. del data['release dates']
  807. if rl:
  808. data['release dates'] = rl
  809. akas = data.get('akas')
  810. nakas = []
  811. for aka in akas:
  812. title = aka.get('title', '').strip()
  813. if not title:
  814. continue
  815. countries = aka.get('countries', '').split('/')
  816. if not countries:
  817. nakas.append(title)
  818. else:
  819. for country in countries:
  820. nakas.append('%s::%s' % (title, country.strip()))
  821. if akas:
  822. del data['akas']
  823. if nakas:
  824. data['akas'] = nakas
  825. return data
  826. class DOMHTMLRatingsParser(DOMParserBase):
  827. """Parser for the "user ratings" page of a given movie.
  828. The page should be provided as a string, as taken from
  829. the akas.imdb.com server. The final result will be a
  830. dictionary, with a key for every relevant section.
  831. Example:
  832. rparser = DOMHTMLRatingsParser()
  833. result = rparser.parse(userratings_html_string)
  834. """
  835. re_means = re.compile('mean\s*=\s*([0-9]\.[0-9])\.\s*median\s*=\s*([0-9])',
  836. re.I)
  837. extractors = [
  838. Extractor(label='number of votes',
  839. path="//td[b='Percentage']/../../tr",
  840. attrs=[Attribute(key='votes',
  841. multi=True,
  842. path={
  843. 'votes': "td[1]//text()",
  844. 'ordinal': "td[3]//text()"
  845. })]),
  846. Extractor(label='mean and median',
  847. path="//p[starts-with(text(), 'Arithmetic mean')]",
  848. attrs=Attribute(key='mean and median',
  849. path="text()")),
  850. Extractor(label='rating',
  851. path="//a[starts-with(@href, '/search/title?user_rating=')]",
  852. attrs=Attribute(key='rating',
  853. path="text()")),
  854. Extractor(label='demographic voters',
  855. path="//td[b='Average']/../../tr",
  856. attrs=Attribute(key='demographic voters',
  857. multi=True,
  858. path={
  859. 'voters': "td[1]//text()",
  860. 'votes': "td[2]//text()",
  861. 'average': "td[3]//text()"
  862. })),
  863. Extractor(label='top 250',
  864. path="//a[text()='top 250']",
  865. attrs=Attribute(key='top 250',
  866. path="./preceding-sibling::text()[1]"))
  867. ]
  868. def postprocess_data(self, data):
  869. nd = {}
  870. votes = data.get('votes', [])
  871. if votes:
  872. nd['number of votes'] = {}
  873. for i in xrange(1, 11):
  874. nd['number of votes'][int(votes[i]['ordinal'])] = \
  875. int(votes[i]['votes'].replace(',', ''))
  876. mean = data.get('mean and median', '')
  877. if mean:
  878. means = self.re_means.findall(mean)
  879. if means and len(means[0]) == 2:
  880. am, med = means[0]
  881. try: am = float(am)
  882. except (ValueError, OverflowError): pass
  883. if type(am) is type(1.0):
  884. nd['arithmetic mean'] = am
  885. try: med = int(med)
  886. except (ValueError, OverflowError): pass
  887. if type(med) is type(0):
  888. nd['median'] = med
  889. if 'rating' in data:
  890. nd['rating'] = float(data['rating'])
  891. dem_voters = data.get('demographic voters')
  892. if dem_voters:
  893. nd['demographic'] = {}
  894. for i in xrange(1, len(dem_voters)):
  895. if (dem_voters[i]['votes'] is not None) \
  896. and (dem_voters[i]['votes'].strip()):
  897. nd['demographic'][dem_voters[i]['voters'].strip().lower()] \
  898. = (int(dem_voters[i]['votes'].replace(',', '')),
  899. float(dem_voters[i]['average']))
  900. if 'imdb users' in nd.get('demographic', {}):
  901. nd['votes'] = nd['demographic']['imdb users'][0]
  902. nd['demographic']['all votes'] = nd['demographic']['imdb users']
  903. del nd['demographic']['imdb users']
  904. top250 = data.get('top 250')
  905. if top250:
  906. sd = top250[9:]
  907. i = sd.find(' ')
  908. if i != -1:
  909. sd = sd[:i]
  910. try: sd = int(sd)
  911. except (ValueError, OverflowError): pass
  912. if type(sd) is type(0):
  913. nd['top 250 rank'] = sd
  914. return nd
  915. class DOMHTMLEpisodesRatings(DOMParserBase):
  916. """Parser for the "episode ratings ... by date" page of a given movie.
  917. The page should be provided as a string, as taken from
  918. the akas.imdb.com server. The final result will be a
  919. dictionary, with a key for every relevant section.
  920. Example:
  921. erparser = DOMHTMLEpisodesRatings()
  922. result = erparser.parse(eprating_html_string)
  923. """
  924. _containsObjects = True
  925. extractors = [Extractor(label='title', path="//title",
  926. attrs=Attribute(key='title', path="./text()")),
  927. Extractor(label='ep ratings',
  928. path="//th/../..//tr",
  929. attrs=Attribute(key='episodes', multi=True,
  930. path={'nr': ".//td[1]/text()",
  931. 'ep title': ".//td[2]//text()",
  932. 'movieID': ".//td[2]/a/@href",
  933. 'rating': ".//td[3]/text()",
  934. 'votes': ".//td[4]/text()"}))]
  935. def postprocess_data(self, data):
  936. if 'title' not in data or 'episodes' not in data: return {}
  937. nd = []
  938. title = data['title']
  939. for i in data['episodes']:
  940. ept = i['ep title']
  941. movieID = analyze_imdbid(i['movieID'])
  942. votes = i['votes']
  943. rating = i['rating']
  944. if not (ept and movieID and votes and rating): continue
  945. try:
  946. votes = int(votes.replace(',', '').replace('.', ''))
  947. except:
  948. pass
  949. try:
  950. rating = float(rating)
  951. except:
  952. pass
  953. ept = ept.strip()
  954. ept = u'%s {%s' % (title, ept)
  955. nr = i['nr']
  956. if nr:
  957. ept += u' (#%s)' % nr.strip()
  958. ept += '}'
  959. if movieID is not None:
  960. movieID = str(movieID)
  961. m = Movie(title=ept, movieID=movieID, accessSystem=self._as,
  962. modFunct=self._modFunct)
  963. epofdict = m.get('episode of')
  964. if epofdict is not None:
  965. m['episode of'] = Movie(data=epofdict, accessSystem=self._as,
  966. modFunct=self._modFunct)
  967. nd.append({'episode': m, 'votes': votes, 'rating': rating})
  968. return {'episodes rating': nd}
  969. def _normalize_href(href):
  970. if (href is not None) and (not href.lower().startswith('http://')):
  971. if href.startswith('/'): href = href[1:]
  972. href = '%s%s' % (imdbURL_base, href)
  973. return href
  974. class DOMHTMLOfficialsitesParser(DOMParserBase):
  975. """Parser for the "official sites", "external reviews", "newsgroup
  976. reviews", "miscellaneous links", "sound clips", "video clips" and
  977. "photographs" pages of a given movie.
  978. The page should be provided as a string, as taken from
  979. the akas.imdb.com server. The final result will be a
  980. dictionary, with a key for every relevant section.
  981. Example:
  982. osparser = DOMHTMLOfficialsitesParser()
  983. result = osparser.parse(officialsites_html_string)
  984. """
  985. kind = 'official sites'
  986. extractors = [
  987. Extractor(label='site',
  988. path="//ol/li/a",
  989. attrs=Attribute(key='self.kind',
  990. multi=True,
  991. path={
  992. 'link': "./@href",
  993. 'info': "./text()"
  994. },
  995. postprocess=lambda x: (x.get('info').strip(),
  996. urllib.unquote(_normalize_href(x.get('link'))))))
  997. ]
  998. class DOMHTMLConnectionParser(DOMParserBase):
  999. """Parser for the "connections" page of a given movie.
  1000. The page should be provided as a string, as taken from
  1001. the akas.imdb.com server. The final result will be a
  1002. dictionary, with a key for every relevant section.
  1003. Example:
  1004. connparser = DOMHTMLConnectionParser()
  1005. result = connparser.parse(connections_html_string)
  1006. """
  1007. _containsObjects = True
  1008. extractors = [Extractor(label='connection',
  1009. group="//div[@class='_imdbpy']",
  1010. group_key="./h5/text()",
  1011. group_key_normalize=lambda x: x.lower(),
  1012. path="./a",
  1013. attrs=Attribute(key=None,
  1014. path={'title': "./text()",
  1015. 'movieID': "./@href"},
  1016. multi=True))]
  1017. preprocessors = [
  1018. ('<h5>', '</div><div class="_imdbpy"><h5>'),
  1019. # To get the movie's year.
  1020. ('</a> (', ' ('),
  1021. ('\n<br/>', '</a>'),
  1022. ('<br/> - ', '::')
  1023. ]
  1024. def postprocess_data(self, data):
  1025. for key in data.keys():
  1026. nl = []
  1027. for v in data[key]:
  1028. title = v['title']
  1029. ts = title.split('::', 1)
  1030. title = ts[0].strip()
  1031. notes = u''
  1032. if len(ts) == 2:
  1033. notes = ts[1].strip()
  1034. m = Movie(title=title,
  1035. movieID=analyze_imdbid(v['movieID']),
  1036. accessSystem=self._as, notes=notes,
  1037. modFunct=self._modFunct)
  1038. nl.append(m)
  1039. data[key] = nl
  1040. if not data: return {}
  1041. return {'connections': data}
  1042. class DOMHTMLLocationsParser(DOMParserBase):
  1043. """Parser for the "locations" page of a given movie.
  1044. The page should be provided as a string, as taken from
  1045. the akas.imdb.com server. The final result will be a
  1046. dictionary, with a key for every relevant section.
  1047. Example:
  1048. lparser = DOMHTMLLocationsParser()
  1049. result = lparser.parse(locations_html_string)
  1050. """
  1051. extractors = [Extractor(label='locations', path="//dt",
  1052. attrs=Attribute(key='locations', multi=True,
  1053. path={'place': ".//text()",
  1054. 'note': "./following-sibling::dd[1]" \
  1055. "//text()"},
  1056. postprocess=lambda x: (u'%s::%s' % (
  1057. x['place'].strip(),
  1058. (x['note'] or u'').strip())).strip(':')))]
  1059. class DOMHTMLTechParser(DOMParserBase):
  1060. """Parser for the "technical", "business", "literature",
  1061. "publicity" (for people) and "contacts (for people) pages of
  1062. a given movie.
  1063. The page should be provided as a string, as taken from
  1064. the akas.imdb.com server. The final result will be a
  1065. dictionary, with a key for every relevant section.
  1066. Example:
  1067. tparser = HTMLTechParser()
  1068. result = tparser.parse(technical_html_string)
  1069. """
  1070. kind = 'tech'
  1071. extractors = [Extractor(label='tech',
  1072. group="//h5",
  1073. group_key="./text()",
  1074. group_key_normalize=lambda x: x.lower(),
  1075. path="./following-sibling::div[1]",
  1076. attrs=Attribute(key=None,
  1077. path=".//text()",
  1078. postprocess=lambda x: [t.strip()
  1079. for t in x.split('\n') if t.strip()]))]
  1080. preprocessors = [

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