bilibili.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import calendar
  4. import datetime
  5. import re
  6. from .common import InfoExtractor
  7. from ..compat import (
  8. compat_etree_fromstring,
  9. compat_str,
  10. compat_parse_qs,
  11. compat_xml_parse_error,
  12. )
  13. from ..utils import (
  14. ExtractorError,
  15. int_or_none,
  16. float_or_none,
  17. xpath_text,
  18. )
  19. class BiliBiliIE(InfoExtractor):
  20. _WORKING = False
  21. _VALID_URL = r'https?://www\.bilibili\.(?:tv|com)/video/av(?P<id>\d+)'
  22. _TESTS = [{
  23. 'url': 'http://www.bilibili.tv/video/av1074402/',
  24. 'md5': '9fa226fe2b8a9a4d5a69b4c6a183417e',
  25. 'info_dict': {
  26. 'id': '1554319',
  27. 'ext': 'mp4',
  28. 'title': '【金坷垃】金泡沫',
  29. 'description': 'md5:ce18c2a2d2193f0df2917d270f2e5923',
  30. 'duration': 308.315,
  31. 'timestamp': 1398012660,
  32. 'upload_date': '20140420',
  33. 'thumbnail': 're:^https?://.+\.jpg',
  34. 'uploader': '菊子桑',
  35. 'uploader_id': '156160',
  36. },
  37. }, {
  38. 'url': 'http://www.bilibili.com/video/av1041170/',
  39. 'info_dict': {
  40. 'id': '1507019',
  41. 'ext': 'mp4',
  42. 'title': '【BD1080P】刀语【诸神&异域】',
  43. 'description': '这是个神奇的故事~每个人不留弹幕不给走哦~切利哦!~',
  44. 'timestamp': 1396530060,
  45. 'upload_date': '20140403',
  46. 'uploader': '枫叶逝去',
  47. 'uploader_id': '520116',
  48. },
  49. }, {
  50. 'url': 'http://www.bilibili.com/video/av4808130/',
  51. 'info_dict': {
  52. 'id': '7802182',
  53. 'ext': 'mp4',
  54. 'title': '【长篇】哆啦A梦443【钉铛】',
  55. 'description': '(2016.05.27)来组合客人的脸吧&amp;amp;寻母六千里锭 抱歉,又轮到周日上班现在才到家 封面www.pixiv.net/member_illust.php?mode=medium&amp;amp;illust_id=56912929',
  56. 'timestamp': 1464564180,
  57. 'upload_date': '20160529',
  58. 'uploader': '喜欢拉面',
  59. 'uploader_id': '151066',
  60. },
  61. }, {
  62. # Missing upload time
  63. 'url': 'http://www.bilibili.com/video/av1867637/',
  64. 'info_dict': {
  65. 'id': '2880301',
  66. 'ext': 'mp4',
  67. 'title': '【HDTV】【喜剧】岳父岳母真难当 (2014)【法国票房冠军】',
  68. 'description': '一个信奉天主教的法国旧式传统资产阶级家庭中有四个女儿。三个女儿却分别找了阿拉伯、犹太、中国丈夫,老夫老妻唯独期盼剩下未嫁的小女儿能找一个信奉天主教的法国白人,结果没想到小女儿找了一位非裔黑人……【这次应该不会跳帧了】',
  69. 'uploader': '黑夜为猫',
  70. 'uploader_id': '610729',
  71. },
  72. 'params': {
  73. # Just to test metadata extraction
  74. 'skip_download': True,
  75. },
  76. 'expected_warnings': ['upload time'],
  77. }]
  78. # BiliBili blocks keys from time to time. The current key is extracted from
  79. # the Android client
  80. # TODO: find the sign algorithm used in the flash player
  81. _APP_KEY = '86385cdc024c0f6c'
  82. def _real_extract(self, url):
  83. mobj = re.match(self._VALID_URL, url)
  84. video_id = mobj.group('id')
  85. webpage = self._download_webpage(url, video_id)
  86. params = compat_parse_qs(self._search_regex(
  87. [r'EmbedPlayer\([^)]+,\s*"([^"]+)"\)',
  88. r'<iframe[^>]+src="https://secure\.bilibili\.com/secure,([^"]+)"'],
  89. webpage, 'player parameters'))
  90. cid = params['cid'][0]
  91. info_xml_str = self._download_webpage(
  92. 'http://interface.bilibili.com/v_cdn_play',
  93. cid, query={'appkey': self._APP_KEY, 'cid': cid},
  94. note='Downloading video info page')
  95. err_msg = None
  96. durls = None
  97. info_xml = None
  98. try:
  99. info_xml = compat_etree_fromstring(info_xml_str.encode('utf-8'))
  100. except compat_xml_parse_error:
  101. info_json = self._parse_json(info_xml_str, video_id, fatal=False)
  102. err_msg = (info_json or {}).get('error_text')
  103. else:
  104. err_msg = xpath_text(info_xml, './message')
  105. if info_xml is not None:
  106. durls = info_xml.findall('./durl')
  107. if not durls:
  108. if err_msg:
  109. raise ExtractorError('%s said: %s' % (self.IE_NAME, err_msg), expected=True)
  110. else:
  111. raise ExtractorError('No videos found!')
  112. entries = []
  113. for durl in durls:
  114. size = xpath_text(durl, ['./filesize', './size'])
  115. formats = [{
  116. 'url': durl.find('./url').text,
  117. 'filesize': int_or_none(size),
  118. }]
  119. for backup_url in durl.findall('./backup_url/url'):
  120. formats.append({
  121. 'url': backup_url.text,
  122. # backup URLs have lower priorities
  123. 'preference': -2 if 'hd.mp4' in backup_url.text else -3,
  124. })
  125. self._sort_formats(formats)
  126. entries.append({
  127. 'id': '%s_part%s' % (cid, xpath_text(durl, './order')),
  128. 'duration': int_or_none(xpath_text(durl, './length'), 1000),
  129. 'formats': formats,
  130. })
  131. title = self._html_search_regex('<h1[^>]+title="([^"]+)">', webpage, 'title')
  132. description = self._html_search_meta('description', webpage)
  133. datetime_str = self._html_search_regex(
  134. r'<time[^>]+datetime="([^"]+)"', webpage, 'upload time', fatal=False)
  135. timestamp = None
  136. if datetime_str:
  137. timestamp = calendar.timegm(datetime.datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M').timetuple())
  138. # TODO 'view_count' requires deobfuscating Javascript
  139. info = {
  140. 'id': compat_str(cid),
  141. 'title': title,
  142. 'description': description,
  143. 'timestamp': timestamp,
  144. 'thumbnail': self._html_search_meta('thumbnailUrl', webpage),
  145. 'duration': float_or_none(xpath_text(info_xml, './timelength'), scale=1000),
  146. }
  147. uploader_mobj = re.search(
  148. r'<a[^>]+href="https?://space\.bilibili\.com/(?P<id>\d+)"[^>]+title="(?P<name>[^"]+)"',
  149. webpage)
  150. if uploader_mobj:
  151. info.update({
  152. 'uploader': uploader_mobj.group('name'),
  153. 'uploader_id': uploader_mobj.group('id'),
  154. })
  155. for entry in entries:
  156. entry.update(info)
  157. if len(entries) == 1:
  158. return entries[0]
  159. else:
  160. for idx, entry in enumerate(entries):
  161. entry['id'] = '%s_part%d' % (video_id, (idx + 1))
  162. return {
  163. '_type': 'multi_video',
  164. 'id': video_id,
  165. 'title': title,
  166. 'description': description,
  167. 'entries': entries,
  168. }