cntv央视_yingshi.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. # coding=utf-8
  2. # !/usr/bin/python
  3. import os.path
  4. import random
  5. import sys
  6. sys.path.append('..')
  7. try:
  8. #from base.spider import Spider as BaseSpider
  9. from base.spider import BaseSpider
  10. except ImportError:
  11. from t4.base.spider import BaseSpider
  12. import json
  13. import time
  14. import base64
  15. import datetime
  16. import re
  17. from urllib import request, parse
  18. from pathlib import Path
  19. import urllib
  20. import urllib.request
  21. """
  22. 配置示例:
  23. t4的配置里ext节点会自动变成api对应query参数extend,但t4的ext字符串不支持路径格式,比如./开头或者.json结尾
  24. api里会自动含有ext参数是base64编码后的选中的筛选条件
  25. 错误示例,ext含有json:
  26. {
  27. "key":"hipy_cntv央视",
  28. "name":"cntv央视(hipy_t4)",
  29. "type":4,
  30. "api":"http://192.168.31.49:5707/api/v1/vod/cntv央视?api_ext={{host}}/txt/hipy/cntv央视.json",
  31. "searchable":1,
  32. "quickSearch":1,
  33. "filterable":0,
  34. "ext":"cntv央视.json"
  35. }
  36. 正确示例。同时存在ext和api_ext会优先取ext作为extend加载init
  37. {
  38. "key":"hipy_t4_cntv央视",
  39. "name":"cntv央视(hipy_t4)",
  40. "type":4,
  41. "api":"http://192.168.31.49:5707/api/v1/vod/cntv央视?api_ext={{host}}/txt/hipy/cntv央视.json",
  42. "searchable":1,
  43. "quickSearch":0,
  44. "filterable":1,
  45. "ext":"{{host}}/files/hipy/cntv央视.json"
  46. },
  47. {
  48. "key": "hipy_t3_cntv央视",
  49. "name": "cntv央视(hipy_t3)",
  50. "type": 3,
  51. "api": "{{host}}/txt/hipy/cntv央视.py",
  52. "searchable": 1,
  53. "quickSearch": 0,
  54. "filterable": 1,
  55. "ext": "{{host}}/files/hipy/cntv央视.json"
  56. },
  57. """
  58. class Spider(BaseSpider): # 元类 默认的元类 type
  59. module = None
  60. def getDependence(self):
  61. return ['base_spider']
  62. def getName(self):
  63. return "中央电视台" # 可搜索
  64. def init_api_ext_file(self):
  65. ext_file = __file__.replace('.py', '.json')
  66. print(f'ext_file:{ext_file}')
  67. # 特别节目网页: https://tv.cctv.com/yxg/index.shtml?spm=C28340.PlFTqGe6Zk8M.E2PQtIunpEaz.65
  68. # 特别节目分类筛选获取页面: https://tv.cctv.com/yxg/tbjm/index.shtml
  69. # 纪录片网页: https://tv.cctv.com/yxg/index.shtml?spm=C28340.PlFTqGe6Zk8M.E2PQtIunpEaz.65
  70. # 纪录片分类筛选获取页面:https://tv.cctv.com/yxg/jlp/index.shtml
  71. # ==================== 获取特别节目的筛选条件 ======================
  72. r = self.fetch('https://tv.cctv.com/yxg/tbjm/index.shtml')
  73. html = r.text
  74. html = self.html(html)
  75. filter_tbjm = []
  76. lis = html.xpath('//*[@id="pindao"]/li')
  77. li_value = []
  78. for li in lis:
  79. li_value.append({
  80. 'n': ''.join(li.xpath('./span//text()')),
  81. 'v': ''.join(li.xpath('@datacd')),
  82. })
  83. # print(li_value)
  84. filter_tbjm.append({
  85. "key": "datapd-channel",
  86. "name": "频道",
  87. "value": li_value
  88. })
  89. lis = html.xpath('//*[@id="fenlei"]/li')
  90. li_value = []
  91. for li in lis:
  92. li_value.append({
  93. 'n': ''.join(li.xpath('./span//text()')),
  94. 'v': ''.join(li.xpath('@datalx')),
  95. })
  96. # print(li_value)
  97. filter_tbjm.append({
  98. "key": "datafl-sc",
  99. "name": "类型",
  100. "value": li_value
  101. })
  102. lis = html.xpath('//*[@id="zimu"]/li')
  103. li_value = []
  104. for li in lis:
  105. li_value.append({
  106. 'n': ''.join(li.xpath('./span//text()')),
  107. 'v': ''.join(li.xpath('@datazm')),
  108. })
  109. # print(li_value)
  110. filter_tbjm.append({
  111. "key": "dataszm-letter",
  112. "name": "首字母",
  113. "value": li_value
  114. })
  115. print(filter_tbjm)
  116. # ==================== 纪录片筛选获取 ======================
  117. r = self.fetch('https://tv.cctv.com/yxg/jlp/index.shtml')
  118. html = r.text
  119. html = self.html(html)
  120. filter_jlp = []
  121. lis = html.xpath('//*[@id="pindao"]/li')
  122. li_value = []
  123. for li in lis:
  124. li_value.append({
  125. 'n': ''.join(li.xpath('./span//text()')),
  126. 'v': ''.join(li.xpath('@datacd')),
  127. })
  128. # print(li_value)
  129. filter_jlp.append({
  130. "key": "datapd-channel",
  131. "name": "频道",
  132. "value": li_value
  133. })
  134. lis = html.xpath('//*[@id="fenlei"]/li')
  135. li_value = []
  136. for li in lis:
  137. li_value.append({
  138. 'n': ''.join(li.xpath('./span//text()')),
  139. 'v': ''.join(li.xpath('@datalx')),
  140. })
  141. # print(li_value)
  142. filter_jlp.append({
  143. "key": "datafl-sc",
  144. "name": "类型",
  145. "value": li_value
  146. })
  147. lis = html.xpath('//*[@id="nianfen"]/li')
  148. li_value = []
  149. for li in lis:
  150. li_value.append({
  151. 'n': ''.join(li.xpath('./span//text()')),
  152. 'v': ''.join(li.xpath('@datanf')),
  153. })
  154. # print(li_value)
  155. filter_jlp.append({
  156. "key": "datanf-year",
  157. "name": "年份",
  158. "value": li_value
  159. })
  160. lis = html.xpath('//*[@id="zimu"]/li')
  161. li_value = []
  162. for li in lis:
  163. li_value.append({
  164. 'n': ''.join(li.xpath('./span//text()')),
  165. 'v': ''.join(li.xpath('@datazm')),
  166. })
  167. # print(li_value)
  168. filter_jlp.append({
  169. "key": "dataszm-letter",
  170. "name": "首字母",
  171. "value": li_value
  172. })
  173. print(filter_jlp)
  174. ext_file_dict = {
  175. "特别节目": filter_tbjm,
  176. "纪录片": filter_jlp,
  177. }
  178. # print(json.dumps(ext_file_dict,ensure_ascii=False,indent=4))
  179. with open(ext_file, mode='w+', encoding='utf-8') as f:
  180. # f.write(json.dumps(ext_file_dict,ensure_ascii=False,indent=4))
  181. f.write(json.dumps(ext_file_dict, ensure_ascii=False))
  182. def init(self, extend=""):
  183. def init_file(ext_file):
  184. ext_file = Path(ext_file).as_posix()
  185. # print(f'ext_file:{ext_file}')
  186. if os.path.exists(ext_file):
  187. # print('存在扩展文件')
  188. with open(ext_file, mode='r', encoding='utf-8') as f:
  189. try:
  190. ext_dict = json.loads(f.read())
  191. # print(ext_dict)
  192. self.config['filter'].update(ext_dict)
  193. except Exception as e:
  194. print(f'更新扩展筛选条件发生错误:{e}')
  195. print("============依赖列表:{0}============".format(extend))
  196. ext = self.extend
  197. print("============ext:{0}============".format(ext))
  198. if isinstance(ext, str) and ext:
  199. if ext.startswith('./'):
  200. ext_file = os.path.join(os.path.dirname(__file__), ext)
  201. init_file(ext_file)
  202. elif ext.startswith('http'):
  203. try:
  204. r = self.fetch(ext)
  205. self.config['filter'].update(r.json())
  206. except Exception as e:
  207. print(f'更新扩展筛选条件发生错误:{e}')
  208. elif not ext.startswith('./') and not ext.startswith('http'):
  209. ext_file = os.path.join(os.path.dirname(__file__), './' + ext + '.json')
  210. init_file(ext_file)
  211. # ==================== 栏目大全加载年月筛选 ======================
  212. lanmu_list = self.config['filter']['栏目大全']
  213. lanmu_keys_list = [lanmu['key'] for lanmu in lanmu_list]
  214. if 'year' not in lanmu_keys_list:
  215. currentYear = datetime.date.today().year
  216. yearList = [{"n": "全部", "v": ""}]
  217. for year in range(currentYear, currentYear - 10, -1):
  218. yearList.append({"n": year, "v": year})
  219. yearDict = {"key": "year", "name": "年份", "value": yearList}
  220. lanmu_list.append(yearDict)
  221. if 'month' not in lanmu_keys_list:
  222. monthList = [{"n": "全部", "v": ""}]
  223. for month in range(1, 13):
  224. text = str(month).rjust(2, '0')
  225. monthList.append({"n": text, "v": text})
  226. monthDict = {"key": "month", "name": "月份", "value": monthList}
  227. lanmu_list.append(monthDict)
  228. # 装载模块,这里只要一个就够了
  229. if isinstance(extend, list):
  230. for lib in extend:
  231. if '.Spider' in str(type(lib)):
  232. self.module = lib
  233. break
  234. def isVideoFormat(self, url):
  235. pass
  236. def manualVideoCheck(self):
  237. pass
  238. def homeContent(self, filter):
  239. result = {}
  240. cateManual = {
  241. "4K专区": "4K专区",
  242. "栏目大全": "栏目大全",
  243. "特别节目": "特别节目",
  244. "纪录片": "纪录片",
  245. "电视剧": "电视剧",
  246. "动画片": "动画片",
  247. "频道直播": "频道直播",
  248. }
  249. classes = []
  250. for k in cateManual:
  251. classes.append({
  252. 'type_name': k,
  253. 'type_id': cateManual[k]
  254. })
  255. result['class'] = classes
  256. if (filter):
  257. result['filters'] = self.config['filter']
  258. return result
  259. def homeVideoContent(self):
  260. result = {
  261. 'list': []
  262. }
  263. if self.module:
  264. result = self.module.homeVideoContent()
  265. return result
  266. def categoryContent(self, tid, pg, filter, extend):
  267. result = {}
  268. month = "" # 月
  269. year = "" # 年
  270. area = '' # 地区
  271. channel = '' # 频道
  272. datafl = '' # 类型
  273. letter = '' # 字母
  274. year_prefix = '' # 栏目大全的年月筛选过滤
  275. pagecount = 24
  276. if tid == '动画片':
  277. id = urllib.parse.quote(tid)
  278. if 'datadq-area' in extend.keys():
  279. area = urllib.parse.quote(extend['datadq-area'])
  280. if 'dataszm-letter' in extend.keys():
  281. letter = extend['dataszm-letter']
  282. if 'datafl-sc' in extend.keys():
  283. datafl = urllib.parse.quote(extend['datafl-sc'])
  284. url = 'https://api.cntv.cn/list/getVideoAlbumList?channelid=CHAL1460955899450127&area={0}&sc={4}&fc={1}&letter={2}&p={3}&n=24&serviceId=tvcctv&topv=1&t=json'.format(
  285. area, id, letter, pg, datafl)
  286. elif tid == '纪录片':
  287. id = urllib.parse.quote(tid)
  288. if 'datapd-channel' in extend.keys():
  289. channel = urllib.parse.quote(extend['datapd-channel'])
  290. if 'datafl-sc' in extend.keys():
  291. datafl = urllib.parse.quote(extend['datafl-sc'])
  292. if 'datanf-year' in extend.keys():
  293. year = extend['datanf-year']
  294. if 'dataszm-letter' in extend.keys():
  295. letter = extend['dataszm-letter']
  296. url = 'https://api.cntv.cn/list/getVideoAlbumList?channelid=CHAL1460955924871139&fc={0}&channel={1}&sc={2}&year={3}&letter={4}&p={5}&n=24&serviceId=tvcctv&topv=1&t=json'.format(
  297. id, channel, datafl, year, letter, pg)
  298. elif tid == '电视剧':
  299. id = urllib.parse.quote(tid)
  300. if 'datafl-sc' in extend.keys():
  301. datafl = urllib.parse.quote(extend['datafl-sc'])
  302. if 'datanf-year' in extend.keys():
  303. year = extend['datanf-year']
  304. if 'dataszm-letter' in extend.keys():
  305. letter = extend['dataszm-letter']
  306. url = 'https://api.cntv.cn/list/getVideoAlbumList?channelid=CHAL1460955853485115&area={0}&sc={1}&fc={2}&year={3}&letter={4}&p={5}&n=24&serviceId=tvcctv&topv=1&t=json'.format(
  307. area, datafl, id, year, letter, pg)
  308. elif tid == '特别节目':
  309. id = urllib.parse.quote(tid)
  310. if 'datapd-channel' in extend.keys():
  311. channel = urllib.parse.quote(extend['datapd-channel'])
  312. if 'datafl-sc' in extend.keys():
  313. datafl = urllib.parse.quote(extend['datafl-sc'])
  314. if 'dataszm-letter' in extend.keys():
  315. letter = extend['dataszm-letter']
  316. url = 'https://api.cntv.cn/list/getVideoAlbumList?channelid=CHAL1460955953877151&channel={0}&sc={1}&fc={2}&bigday=&letter={3}&p={4}&n=24&serviceId=tvcctv&topv=1&t=json'.format(
  317. channel, datafl, id, letter, pg)
  318. elif tid == '栏目大全':
  319. cid = '' # 频道
  320. if 'cid' in extend.keys():
  321. cid = extend['cid']
  322. fc = '' # 分类
  323. if 'fc' in extend.keys():
  324. fc = extend['fc']
  325. fl = '' # 字母
  326. if 'fl' in extend.keys():
  327. fl = extend['fl']
  328. year = extend.get('year') or ''
  329. month = extend.get('month') or ''
  330. if year:
  331. year_prefix = year + month
  332. url = 'https://api.cntv.cn/lanmu/columnSearch?&fl={0}&fc={1}&cid={2}&p={3}&n=20&serviceId=tvcctv&t=json&cb=ko'.format(
  333. fl, fc, cid, pg)
  334. pagecount = 20
  335. elif tid == '4K专区':
  336. cid = 'CHAL1558416868484111'
  337. url = 'https://api.cntv.cn/NewVideo/getLastVideoList4K?serviceId=cctv4k&cid={0}&p={1}&n={2}&t=json&cb=ko'.format(
  338. cid, pg, pagecount
  339. )
  340. elif tid == '频道直播':
  341. url = 'https://tv.cctv.com/epg/index.shtml'
  342. else:
  343. url = 'https://tv.cctv.com/epg/index.shtml'
  344. videos = []
  345. htmlText = self.webReadFile(urlStr=url, header=self.header)
  346. if tid == '栏目大全':
  347. index = htmlText.rfind(');')
  348. if index > -1:
  349. htmlText = htmlText[3:index]
  350. videos = self.get_list1(html=htmlText, tid=tid, year_prefix=year_prefix)
  351. elif tid == '4K专区':
  352. index = htmlText.rfind(');')
  353. if index > -1:
  354. htmlText = htmlText[3:index]
  355. videos = self.get_list_4k(html=htmlText, tid=tid)
  356. elif tid == '频道直播':
  357. html = self.html(htmlText)
  358. lis = html.xpath('//*[@id="jiemudan01"]//div[contains(@class,"channel_con")]//ul/li')
  359. for li in lis:
  360. vid = ''.join(li.xpath('./img/@title'))
  361. pic = ''.join(li.xpath('./img/@src'))
  362. pic = self.urljoin('https://tv.cctv.com/epg/index.shtml', pic)
  363. videos.append({
  364. 'vod_id': '||'.join([tid, vid, f'https://tv.cctv.com/live/{vid}/', pic]),
  365. 'vod_name': vid,
  366. 'vod_pic': pic,
  367. 'vod_mark': '',
  368. })
  369. else:
  370. videos = self.get_list(html=htmlText, tid=tid)
  371. # print(videos)
  372. result['list'] = videos
  373. result['page'] = pg
  374. result['pagecount'] = 9999 if len(videos) >= pagecount else pg
  375. result['limit'] = 90
  376. result['total'] = 999999
  377. return result
  378. def detailContent(self, array):
  379. result = {}
  380. year_prefix = ''
  381. did = array[0]
  382. if '$$$' in did:
  383. year_prefix = did.split('$$$')[0]
  384. did = did.split('$$$')[1]
  385. aid = did.split('||')
  386. tid = aid[0]
  387. title = aid[1]
  388. lastVideo = aid[2]
  389. logo = aid[3]
  390. if tid == '频道直播':
  391. vod = {
  392. "vod_id": did,
  393. "vod_name": title.replace(' ', ''),
  394. "vod_pic": logo,
  395. "vod_content": f'频道{title}正在直播中',
  396. "vod_play_from": '道长在线直播',
  397. "vod_play_url": f'在线观看${title}||{lastVideo}',
  398. }
  399. result = {'list': [vod]}
  400. return result
  401. id = aid[4]
  402. vod_year = aid[5]
  403. actors = aid[6] if len(aid) > 6 else ''
  404. brief = aid[7] if len(aid) > 7 else '' # get请求最长255,这个描述会有可能直接被干没了。
  405. fromId = 'CCTV'
  406. if tid == "栏目大全":
  407. lastUrl = 'https://api.cntv.cn/video/videoinfoByGuid?guid={0}&serviceId=tvcctv'.format(id)
  408. htmlTxt = self.webReadFile(urlStr=lastUrl, header=self.header)
  409. topicId = json.loads(htmlTxt)['ctid']
  410. url = 'https://api.cntv.cn/NewVideo/getVideoListByColumn'
  411. Url = "{0}?id={1}&d=&p=1&n=100&sort=desc&mode=0&serviceId=tvcctv&t=json&d={2}".format(
  412. url, topicId, year_prefix)
  413. elif tid == "4K专区":
  414. Url = 'https://api.cntv.cn/NewVideo/getVideoListByAlbumIdNew?id={0}&serviceId=cctv4k&p=1&n=100&mode=0&pub=1'.format(
  415. id)
  416. print(Url)
  417. else:
  418. Url = 'https://api.cntv.cn/NewVideo/getVideoListByAlbumIdNew?id={0}&serviceId=tvcctv&p=1&n=100&mode=0&pub=1'.format(
  419. id)
  420. jRoot = ''
  421. videoList = []
  422. try:
  423. if tid == "搜索":
  424. fromId = '中央台'
  425. videoList = [title + "$" + lastVideo]
  426. else:
  427. htmlTxt = self.webReadFile(urlStr=Url, header=self.header)
  428. jRoot = json.loads(htmlTxt)
  429. data = jRoot['data']
  430. jsonList = data['list']
  431. videoList = self.get_EpisodesList(jsonList=jsonList)
  432. if len(videoList) < 1:
  433. htmlTxt = self.webReadFile(urlStr=lastVideo, header=self.header)
  434. if tid == "电视剧" or tid == "纪录片" or tid == "4K专区":
  435. patternTxt = r"'title':\s*'(?P<title>.+?)',\n{0,1}\s*'brief':\s*'(.+?)',\n{0,1}\s*'img':\s*'(.+?)',\n{0,1}\s*'url':\s*'(?P<url>.+?)'"
  436. elif tid == "特别节目":
  437. patternTxt = r'class="tp1"><a\s*href="(?P<url>https://.+?)"\s*target="_blank"\s*title="(?P<title>.+?)"></a></div>'
  438. elif tid == "动画片":
  439. patternTxt = r"'title':\s*'(?P<title>.+?)',\n{0,1}\s*'img':\s*'(.+?)',\n{0,1}\s*'brief':\s*'(.+?)',\n{0,1}\s*'url':\s*'(?P<url>.+?)'"
  440. elif tid == "栏目大全":
  441. patternTxt = r'href="(?P<url>.+?)" target="_blank" alt="(?P<title>.+?)" title=".+?">'
  442. videoList = self.get_EpisodesList_re(htmlTxt=htmlTxt, patternTxt=patternTxt)
  443. fromId = '央视'
  444. except:
  445. pass
  446. if len(videoList) == 0:
  447. return {}
  448. vod = {
  449. "vod_id": did,
  450. "vod_name": title.replace(' ', ''),
  451. "vod_pic": logo,
  452. "type_name": tid,
  453. "vod_year": vod_year,
  454. "vod_area": "",
  455. "vod_remarks": '',
  456. "vod_actor": actors,
  457. "vod_director": '',
  458. "vod_content": brief
  459. }
  460. vod['vod_play_from'] = fromId
  461. vod['vod_play_url'] = "#".join(videoList)
  462. result = {
  463. 'list': [
  464. vod
  465. ]
  466. }
  467. return result
  468. def get_lineList(self, Txt, mark, after):
  469. circuit = []
  470. origin = Txt.find(mark)
  471. while origin > 8:
  472. end = Txt.find(after, origin)
  473. circuit.append(Txt[origin:end])
  474. origin = Txt.find(mark, end)
  475. return circuit
  476. def get_RegexGetTextLine(self, Text, RegexText, Index):
  477. returnTxt = []
  478. pattern = re.compile(RegexText, re.M | re.S)
  479. ListRe = pattern.findall(Text)
  480. if len(ListRe) < 1:
  481. return returnTxt
  482. for value in ListRe:
  483. returnTxt.append(value)
  484. return returnTxt
  485. def searchContent(self, key, quick, pg=1):
  486. key = urllib.parse.quote(key)
  487. Url = 'https://search.cctv.com/ifsearch.php?page=1&qtext={0}&sort=relevance&pageSize=20&type=video&vtime=-1&datepid=1&channel=&pageflag=0&qtext_str={0}'.format(
  488. key)
  489. htmlTxt = self.webReadFile(urlStr=Url, header=self.header)
  490. videos = self.get_list_search(html=htmlTxt, tid='搜索')
  491. result = {
  492. 'list': videos
  493. }
  494. return result
  495. def playerContent(self, flag, id, vipFlags):
  496. result = {}
  497. url = ''
  498. parse = 0
  499. headers = {
  500. 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'
  501. }
  502. if flag == 'CCTV':
  503. url = self.get_m3u8(urlTxt=id)
  504. elif flag == '道长在线直播':
  505. # _url = id
  506. title = id.split('||')[0] # 获取标题
  507. _url = f'https://vdn.live.cntv.cn/api2/liveHtml5.do?channel=pc://cctv_p2p_hd{title}&channel_id={title}'
  508. htmlTxt = self.webReadFile(urlStr=_url, header=self.header)
  509. vdata = self.regStr(htmlTxt, "var .*?=.*?'(.*?)';")
  510. vdata = self.str2json(vdata)
  511. print(vdata)
  512. url = vdata['hls_url']['hls1']
  513. print(url)
  514. url = self.fixm3u8_url(url)
  515. else:
  516. try:
  517. htmlTxt = self.webReadFile(urlStr=id, header=self.header)
  518. guid = self.get_RegexGetText(Text=htmlTxt, RegexText=r'var\sguid\s*=\s*"(.+?)";', Index=1)
  519. url = self.get_m3u8(urlTxt=guid)
  520. except:
  521. url = id
  522. parse = 1
  523. if url.find('https:') < 0:
  524. url = id
  525. parse = 1
  526. result["parse"] = parse # 1=嗅探,0=播放
  527. result["playUrl"] = ''
  528. result["url"] = url
  529. result["header"] = headers
  530. return result
  531. # 分类抓取地址:
  532. # 栏目大全:https://tv.cctv.com/lm/index.shtml?spm=C28340.Pu9TN9YUsfNZ.E2PQtIunpEaz.24
  533. # 电视剧:https://tv.cctv.com/yxg/index.shtml?spm=C28340.PlFTqGe6Zk8M.E2PQtIunpEaz.65#datacid=dsj&datafl=&datadq=&fc=%E7%94%B5%E8%A7%86%E5%89%A7&datanf=&dataszm=
  534. # 动画片:https://tv.cctv.com/yxg/index.shtml?spm=C28340.PlFTqGe6Zk8M.E2PQtIunpEaz.65#datacid=dhp&datafl=&datadq=&fc=%E5%8A%A8%E7%94%BB%E7%89%87&dataszm=
  535. # 记录片:https://tv.cctv.com/yxg/index.shtml?spm=C28340.PlFTqGe6Zk8M.E2PQtIunpEaz.65#datacid=jlp&datapd=&datafl=&fc=%E7%BA%AA%E5%BD%95%E7%89%87&datanf=&dataszm=
  536. # 特别节目:https://tv.cctv.com/yxg/index.shtml?spm=C28340.PlFTqGe6Zk8M.E2PQtIunpEaz.65#datacid=tbjm&datapd=&datafl=&fc=%E7%89%B9%E5%88%AB%E8%8A%82%E7%9B%AE&datajr=&dataszm=
  537. config = {
  538. "player": {},
  539. "filter": {
  540. "电视剧": [
  541. {"key": "datafl-sc", "name": "类型",
  542. "value": [{"n": "全部", "v": ""}, {"n": "谍战", "v": "谍战"}, {"n": "悬疑", "v": "悬疑"},
  543. {"n": "刑侦", "v": "刑侦"}, {"n": "历史", "v": "历史"}, {"n": "古装", "v": "古装"},
  544. {"n": "武侠", "v": "武侠"}, {"n": "军旅", "v": "军旅"}, {"n": "战争", "v": "战争"},
  545. {"n": "喜剧", "v": "喜剧"}, {"n": "青春", "v": "青春"}, {"n": "言情", "v": "言情"},
  546. {"n": "偶像", "v": "偶像"}, {"n": "家庭", "v": "家庭"}, {"n": "年代", "v": "年代"},
  547. {"n": "革命", "v": "革命"}, {"n": "农村", "v": "农村"}, {"n": "都市", "v": "都市"},
  548. {"n": "其他", "v": "其他"}]},
  549. {"key": "datadq-area", "name": "地区",
  550. "value": [{"n": "全部", "v": ""}, {"n": "中国大陆", "v": "中国大陆"}, {"n": "中国香港", "v": "香港"},
  551. {"n": "美国", "v": "美国"}, {"n": "欧洲", "v": "欧洲"}, {"n": "泰国", "v": "泰国"}]},
  552. {"key": "datanf-year", "name": "年份",
  553. "value": [{"n": "全部", "v": ""}, {"n": "2024", "v": "2024"}, {"n": "2023", "v": "2023"},
  554. {"n": "2022", "v": "2022"},
  555. {"n": "2021", "v": "2021"}, {"n": "2020", "v": "2020"}, {"n": "2019", "v": "2019"},
  556. {"n": "2018", "v": "2018"}, {"n": "2017", "v": "2017"}, {"n": "2016", "v": "2016"},
  557. {"n": "2015", "v": "2015"}, {"n": "2014", "v": "2014"}, {"n": "2013", "v": "2013"},
  558. {"n": "2012", "v": "2012"}, {"n": "2011", "v": "2011"}, {"n": "2010", "v": "2010"},
  559. {"n": "2009", "v": "2009"}, {"n": "2008", "v": "2008"}, {"n": "2007", "v": "2007"},
  560. {"n": "2006", "v": "2006"}, {"n": "2005", "v": "2005"}, {"n": "2004", "v": "2004"},
  561. {"n": "2003", "v": "2003"}, {"n": "2002", "v": "2002"}, {"n": "2001", "v": "2001"},
  562. {"n": "2000", "v": "2000"}, {"n": "1999", "v": "1999"}, {"n": "1998", "v": "1998"},
  563. {"n": "1997", "v": "1997"}]},
  564. {"key": "dataszm-letter", "name": "字母",
  565. "value": [{"n": "全部", "v": ""}, {"n": "A", "v": "A"}, {"n": "C", "v": "C"}, {"n": "E", "v": "E"},
  566. {"n": "F", "v": "F"}, {"n": "G", "v": "G"}, {"n": "H", "v": "H"}, {"n": "I", "v": "I"},
  567. {"n": "J", "v": "J"}, {"n": "K", "v": "K"}, {"n": "L", "v": "L"}, {"n": "M", "v": "M"},
  568. {"n": "N", "v": "N"}, {"n": "O", "v": "O"}, {"n": "P", "v": "P"}, {"n": "Q", "v": "Q"},
  569. {"n": "R", "v": "R"}, {"n": "S", "v": "S"}, {"n": "T", "v": "T"}, {"n": "U", "v": "U"},
  570. {"n": "V", "v": "V"}, {"n": "W", "v": "W"}, {"n": "X", "v": "X"}, {"n": "Y", "v": "Y"},
  571. {"n": "Z", "v": "Z"}, {"n": "0-9", "v": "0-9"}]}
  572. ],
  573. "动画片": [
  574. {"key": "datafl-sc", "name": "类型",
  575. "value": [{"n": "全部", "v": ""}, {"n": "亲子", "v": "亲子"}, {"n": "搞笑", "v": "搞笑"},
  576. {"n": "冒险", "v": "冒险"}, {"n": "动作", "v": "动作"}, {"n": "宠物", "v": "宠物"},
  577. {"n": "体育", "v": "体育"}, {"n": "益智", "v": "益智"}, {"n": "历史", "v": "历史"},
  578. {"n": "教育", "v": "教育"}, {"n": "校园", "v": "校园"}, {"n": "言情", "v": "言情"},
  579. {"n": "武侠", "v": "武侠"}, {"n": "经典", "v": "经典"}, {"n": "未来", "v": "未来"},
  580. {"n": "古代", "v": "古代"}, {"n": "神话", "v": "神话"}, {"n": "真人", "v": "真人"},
  581. {"n": "励志", "v": "励志"}, {"n": "热血", "v": "热血"}, {"n": "奇幻", "v": "奇幻"},
  582. {"n": "童话", "v": "童话"}, {"n": "剧情", "v": "剧情"}, {"n": "夺宝", "v": "夺宝"},
  583. {"n": "其他", "v": "其他"}]},
  584. {"key": "datadq-area", "name": "地区",
  585. "value": [{"n": "全部", "v": ""}, {"n": "中国大陆", "v": "中国大陆"}, {"n": "美国", "v": "美国"},
  586. {"n": "欧洲", "v": "欧洲"}]},
  587. {"key": "dataszm-letter", "name": "字母",
  588. "value": [{"n": "全部", "v": ""}, {"n": "A", "v": "A"}, {"n": "C", "v": "C"}, {"n": "E", "v": "E"},
  589. {"n": "F", "v": "F"}, {"n": "G", "v": "G"}, {"n": "H", "v": "H"}, {"n": "I", "v": "I"},
  590. {"n": "J", "v": "J"}, {"n": "K", "v": "K"}, {"n": "L", "v": "L"}, {"n": "M", "v": "M"},
  591. {"n": "N", "v": "N"}, {"n": "O", "v": "O"}, {"n": "P", "v": "P"}, {"n": "Q", "v": "Q"},
  592. {"n": "R", "v": "R"}, {"n": "S", "v": "S"}, {"n": "T", "v": "T"}, {"n": "U", "v": "U"},
  593. {"n": "V", "v": "V"}, {"n": "W", "v": "W"}, {"n": "X", "v": "X"}, {"n": "Y", "v": "Y"},
  594. {"n": "Z", "v": "Z"}, {"n": "0-9", "v": "0-9"}]}
  595. ],
  596. "纪录片": [
  597. {"key": "datafl-sc", "name": "类型",
  598. "value": [{"n": "全部", "v": ""}, {"n": "人文历史", "v": "人文历史"}, {"n": "人物", "v": "人物"},
  599. {"n": "军事", "v": "军事"}, {"n": "探索", "v": "探索"}, {"n": "社会", "v": "社会"},
  600. {"n": "时政", "v": "时政"}, {"n": "经济", "v": "经济"}, {"n": "科技", "v": "科技"}]},
  601. {"key": "datanf-year", "name": "年份",
  602. "value": [{"n": "全部", "v": ""}, {"n": "2024", "v": "2024"}, {"n": "2023", "v": "2023"},
  603. {"n": "2022", "v": "2022"},
  604. {"n": "2021", "v": "2021"}, {"n": "2020", "v": "2020"}, {"n": "2019", "v": "2019"},
  605. {"n": "2018", "v": "2018"}, {"n": "2017", "v": "2017"}, {"n": "2016", "v": "2016"},
  606. {"n": "2015", "v": "2015"}, {"n": "2014", "v": "2014"}, {"n": "2013", "v": "2013"},
  607. {"n": "2012", "v": "2012"}, {"n": "2011", "v": "2011"}, {"n": "2010", "v": "2010"},
  608. {"n": "2009", "v": "2009"}, {"n": "2008", "v": "2008"}]},
  609. {"key": "dataszm-letter", "name": "字母",
  610. "value": [{"n": "全部", "v": ""}, {"n": "A", "v": "A"}, {"n": "C", "v": "C"}, {"n": "E", "v": "E"},
  611. {"n": "F", "v": "F"}, {"n": "G", "v": "G"}, {"n": "H", "v": "H"}, {"n": "I", "v": "I"},
  612. {"n": "J", "v": "J"}, {"n": "K", "v": "K"}, {"n": "L", "v": "L"}, {"n": "M", "v": "M"},
  613. {"n": "N", "v": "N"}, {"n": "O", "v": "O"}, {"n": "P", "v": "P"}, {"n": "Q", "v": "Q"},
  614. {"n": "R", "v": "R"}, {"n": "S", "v": "S"}, {"n": "T", "v": "T"}, {"n": "U", "v": "U"},
  615. {"n": "V", "v": "V"}, {"n": "W", "v": "W"}, {"n": "X", "v": "X"}, {"n": "Y", "v": "Y"},
  616. {"n": "Z", "v": "Z"}, {"n": "0-9", "v": "0-9"}]}
  617. ],
  618. "特别节目": [
  619. {"key": "datafl-sc", "name": "类型",
  620. "value": [{"n": "全部", "v": ""}, {"n": "全部", "v": "全部"}, {"n": "新闻", "v": "新闻"},
  621. {"n": "经济", "v": "经济"}, {"n": "综艺", "v": "综艺"}, {"n": "体育", "v": "体育"},
  622. {"n": "军事", "v": "军事"}, {"n": "影视", "v": "影视"}, {"n": "科教", "v": "科教"},
  623. {"n": "戏曲", "v": "戏曲"}, {"n": "青少", "v": "青少"}, {"n": "音乐", "v": "音乐"},
  624. {"n": "社会", "v": "社会"}, {"n": "公益", "v": "公益"}, {"n": "其他", "v": "其他"}]},
  625. {"key": "dataszm-letter", "name": "字母",
  626. "value": [{"n": "全部", "v": ""}, {"n": "A", "v": "A"}, {"n": "C", "v": "C"}, {"n": "E", "v": "E"},
  627. {"n": "F", "v": "F"}, {"n": "G", "v": "G"}, {"n": "H", "v": "H"}, {"n": "I", "v": "I"},
  628. {"n": "J", "v": "J"}, {"n": "K", "v": "K"}, {"n": "L", "v": "L"}, {"n": "M", "v": "M"},
  629. {"n": "N", "v": "N"}, {"n": "O", "v": "O"}, {"n": "P", "v": "P"}, {"n": "Q", "v": "Q"},
  630. {"n": "R", "v": "R"}, {"n": "S", "v": "S"}, {"n": "T", "v": "T"}, {"n": "U", "v": "U"},
  631. {"n": "V", "v": "V"}, {"n": "W", "v": "W"}, {"n": "X", "v": "X"}, {"n": "Y", "v": "Y"},
  632. {"n": "Z", "v": "Z"}, {"n": "0-9", "v": "0-9"}]}
  633. ],
  634. "栏目大全": [{"key": "cid", "name": "频道",
  635. "value": [{"n": "全部", "v": ""}, {"n": "CCTV-1综合", "v": "EPGC1386744804340101"},
  636. {"n": "CCTV-2财经", "v": "EPGC1386744804340102"},
  637. {"n": "CCTV-3综艺", "v": "EPGC1386744804340103"},
  638. {"n": "CCTV-4中文国际", "v": "EPGC1386744804340104"},
  639. {"n": "CCTV-5体育", "v": "EPGC1386744804340107"},
  640. {"n": "CCTV-6电影", "v": "EPGC1386744804340108"},
  641. {"n": "CCTV-7国防军事", "v": "EPGC1386744804340109"},
  642. {"n": "CCTV-8电视剧", "v": "EPGC1386744804340110"},
  643. {"n": "CCTV-9纪录", "v": "EPGC1386744804340112"},
  644. {"n": "CCTV-10科教", "v": "EPGC1386744804340113"},
  645. {"n": "CCTV-11戏曲", "v": "EPGC1386744804340114"},
  646. {"n": "CCTV-12社会与法", "v": "EPGC1386744804340115"},
  647. {"n": "CCTV-13新闻", "v": "EPGC1386744804340116"},
  648. {"n": "CCTV-14少儿", "v": "EPGC1386744804340117"},
  649. {"n": "CCTV-15音乐", "v": "EPGC1386744804340118"},
  650. {"n": "CCTV-16奥林匹克", "v": "EPGC1634630207058998"},
  651. {"n": "CCTV-17农业农村", "v": "EPGC1563932742616872"},
  652. {"n": "CCTV-5+体育赛事", "v": "EPGC1468294755566101"}]},
  653. {"key": "fc", "name": "分类",
  654. "value": [{"n": "全部", "v": ""}, {"n": "新闻", "v": "新闻"}, {"n": "体育", "v": "体育"},
  655. {"n": "综艺", "v": "综艺"}, {"n": "健康", "v": "健康"}, {"n": "生活", "v": "生活"},
  656. {"n": "科教", "v": "科教"}, {"n": "经济", "v": "经济"}, {"n": "农业", "v": "农业"},
  657. {"n": "法治", "v": "法治"}, {"n": "军事", "v": "军事"}, {"n": "少儿", "v": "少儿"},
  658. {"n": "动画", "v": "动画"}, {"n": "纪实", "v": "纪实"}, {"n": "戏曲", "v": "戏曲"},
  659. {"n": "音乐", "v": "音乐"}, {"n": "影视", "v": "影视"}]},
  660. {"key": "fl", "name": "字母",
  661. "value": [{"n": "全部", "v": ""}, {"n": "A", "v": "A"}, {"n": "B", "v": "B"},
  662. {"n": "C", "v": "C"}, {"n": "D", "v": "D"}, {"n": "E", "v": "E"},
  663. {"n": "F", "v": "F"}, {"n": "G", "v": "G"}, {"n": "H", "v": "H"},
  664. {"n": "I", "v": "I"}, {"n": "J", "v": "J"}, {"n": "K", "v": "K"},
  665. {"n": "L", "v": "L"}, {"n": "M", "v": "M"}, {"n": "N", "v": "N"},
  666. {"n": "O", "v": "O"}, {"n": "P", "v": "P"}, {"n": "Q", "v": "Q"},
  667. {"n": "R", "v": "R"}, {"n": "S", "v": "S"}, {"n": "T", "v": "T"},
  668. {"n": "U", "v": "U"}, {"n": "V", "v": "V"}, {"n": "W", "v": "W"},
  669. {"n": "X", "v": "X"}, {"n": "Y", "v": "Y"}, {"n": "Z", "v": "Z"}]},
  670. ]
  671. }
  672. }
  673. header = {
  674. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36",
  675. "Host": "tv.cctv.com",
  676. "Referer": "https://tv.cctv.com/"
  677. }
  678. def localProxy(self, params):
  679. return [200, "video/MP2T", ""]
  680. # -----------------------------------------------自定义函数-----------------------------------------------
  681. # 访问网页
  682. def webReadFile(self, urlStr, header):
  683. html = ''
  684. req = urllib.request.Request(url=urlStr) # ,headers=header
  685. with urllib.request.urlopen(req) as response:
  686. html = response.read().decode('utf-8')
  687. return html
  688. # 判断网络地址是否存在
  689. def TestWebPage(self, urlStr, header):
  690. html = ''
  691. req = urllib.request.Request(url=urlStr, method='HEAD') # ,headers=header
  692. with urllib.request.urlopen(req) as response:
  693. html = response.getcode()
  694. return html
  695. # 正则取文本
  696. def get_RegexGetText(self, Text, RegexText, Index):
  697. returnTxt = ""
  698. Regex = re.search(RegexText, Text, re.M | re.S)
  699. if Regex is None:
  700. returnTxt = ""
  701. else:
  702. returnTxt = Regex.group(Index)
  703. return returnTxt
  704. # 取集数
  705. def get_EpisodesList(self, jsonList):
  706. videos = []
  707. for vod in jsonList:
  708. url = vod['guid']
  709. title = vod['title']
  710. if len(url) == 0:
  711. continue
  712. videos.append(title + "$" + url)
  713. return videos
  714. # 取集数
  715. def get_EpisodesList_re(self, htmlTxt, patternTxt):
  716. ListRe = re.finditer(patternTxt, htmlTxt, re.M | re.S)
  717. videos = []
  718. for vod in ListRe:
  719. url = vod.group('url')
  720. title = vod.group('title')
  721. if len(url) == 0:
  722. continue
  723. videos.append(title + "$" + url)
  724. return videos
  725. # 取剧集区
  726. def get_lineList(self, Txt, mark, after):
  727. circuit = []
  728. origin = Txt.find(mark)
  729. while origin > 8:
  730. end = Txt.find(after, origin)
  731. circuit.append(Txt[origin:end])
  732. origin = Txt.find(mark, end)
  733. return circuit
  734. # 正则取文本,返回数组
  735. def get_RegexGetTextLine(self, Text, RegexText, Index):
  736. returnTxt = []
  737. pattern = re.compile(RegexText, re.M | re.S)
  738. ListRe = pattern.findall(Text)
  739. if len(ListRe) < 1:
  740. return returnTxt
  741. for value in ListRe:
  742. returnTxt.append(value)
  743. return returnTxt
  744. # 删除html标签
  745. def removeHtml(self, txt):
  746. soup = re.compile(r'<[^>]+>', re.S)
  747. txt = soup.sub('', txt)
  748. return txt.replace("&nbsp;", " ")
  749. def hookM3u8(self, url):
  750. """
  751. https://www.52pojie.cn/thread-1932358-1-1.html
  752. JavaScript:$.ajaxSettings.async = false; var s = ""; let a = $.get(vodh5player.playerList[0].ads.contentSrc); for (var m = 0; m < a.responseText.match(/asp.*?m3u8/g).length; m++) { s = s + "https://hls.cntv.myalicdn.com//asp" + a.responseText.match(/asp.*?m3u8/g)[m].slice(7) + "\n\n" }; var blob = new Blob([s], { type: "text/plain" }); var url = URL.createObjectURL(blob); window.open(url);
  753. @param url:
  754. @return:
  755. """
  756. url = url or ''
  757. hook1 = lambda x: x.replace('asp/', 'asp//', 1)
  758. hook2 = lambda x: x.replace('hls/', 'hls//', 1)
  759. hook3 = lambda x: x.replace('https://newcntv.qcloudcdn.com', 'https://hls.cntv.myalicdn.com/', 1)
  760. hooks = [hook1, hook2, hook3]
  761. hook = random.choice(hooks)
  762. return hook(url)
  763. # 取m3u8
  764. def get_m3u8(self, urlTxt):
  765. """
  766. https://blog.csdn.net/panwang666/article/details/135347859
  767. JavaScript:jQuery.getJSON("https://vdn.apps.cntv.cn/api/getHttpVideoInfo.do?pid="+guid,function(result){document.writeln(result.hls_url.link(result.hls_url));});
  768. https://newcntv.qcloudcdn.com/asp/hls/main/0303000a/3/default/3628bb15af644f588dc91ec68425b9ac/main.m3u8?maxbr=2048
  769. @param urlTxt:
  770. @return:
  771. """
  772. url = "https://vdn.apps.cntv.cn/api/getHttpVideoInfo.do?pid={0}".format(urlTxt)
  773. htmlTxt = self.webReadFile(urlStr=url, header=self.header)
  774. jo = json.loads(htmlTxt)
  775. link = jo['hls_url'].strip()
  776. # print('hls_url:',link)
  777. # 获取域名前缀
  778. urlPrefix = self.get_RegexGetText(Text=link, RegexText='(http[s]?://[a-zA-z0-9.]+)/', Index=1)
  779. # 域名前缀指定替换,然后可以获取到更高质量的视频列表
  780. # /asp/h5e/hls/2000/0303000a/3/default/3628bb15af644f588dc91ec68425b9ac/2000.m3u8
  781. new_link = link.replace(f'{urlPrefix}/asp/hls/', 'https://dh5.cntv.qcloudcdn.com/asp/h5e/hls/').split('?')[0]
  782. # print('new_link:',new_link)
  783. html = self.webReadFile(urlStr=new_link, header=self.header)
  784. content = html.strip()
  785. arr = content.split('\n')
  786. subUrl = arr[-1].split('/')
  787. # hdUrl = urlPrefix + arr[-1]
  788. # subUrl[3] = '2000'
  789. # subUrl[-1] = '2000.m3u8'
  790. # hdUrl = urlPrefix + '/'.join(subUrl)
  791. maxVideo = subUrl[-1].replace('.m3u8', '')
  792. hdUrl = link.replace('main', maxVideo)
  793. hdUrl = hdUrl.replace(urlPrefix, 'https://newcntv.qcloudcdn.com')
  794. hdRsp = self.TestWebPage(urlStr=hdUrl, header=self.header)
  795. if hdRsp == 200:
  796. url = hdUrl.split('?')[0]
  797. url = self.hookM3u8(url)
  798. self.log(f'视频链接: {url}')
  799. else:
  800. url = ''
  801. return url
  802. def fixm3u8_url(self, url):
  803. # 获取域名前缀
  804. urlPrefix = self.get_RegexGetText(Text=url, RegexText='(http[s]?://[a-zA-z0-9.]+)/', Index=1)
  805. # 域名前缀指定替换,然后可以获取到更高质量的视频列表
  806. new_link = url.split('?')[0]
  807. # print(new_link)
  808. html = self.webReadFile(urlStr=new_link, header=self.header)
  809. content = html.strip()
  810. # print(content)
  811. arr = content.split('\n')
  812. subUrl = arr[3] if 'EXT-X-VERSION' in content else arr[2]
  813. hdUrl = self.urljoin(new_link, subUrl).split('?')[0]
  814. # hdUrl = hdUrl.replace(urlPrefix, 'https://newcntv.qcloudcdn.com')
  815. hdRsp = self.TestWebPage(urlStr=hdUrl, header=self.header)
  816. if hdRsp == 200:
  817. url = hdUrl
  818. self.log(f'视频链接: {url}')
  819. else:
  820. url = ''
  821. return url
  822. # 搜索
  823. def get_list_search(self, html, tid):
  824. jRoot = json.loads(html)
  825. jsonList = jRoot['list']
  826. videos = []
  827. for vod in jsonList:
  828. url = vod['urllink']
  829. title = self.removeHtml(txt=vod['title'])
  830. img = vod['imglink']
  831. id = vod['id']
  832. brief = vod['channel']
  833. year = vod['uploadtime']
  834. if len(url) == 0:
  835. continue
  836. guids = [tid, title, url, img, id, year, '', brief]
  837. guid = "||".join(guids)
  838. videos.append({
  839. "vod_id": guid,
  840. "vod_name": title,
  841. "vod_pic": img,
  842. "vod_remarks": year
  843. })
  844. return videos
  845. def get_list1(self, html, tid, year_prefix=None):
  846. jRoot = json.loads(html)
  847. videos = []
  848. data = jRoot['response']
  849. if data is None:
  850. return []
  851. jsonList = data['docs']
  852. for vod in jsonList:
  853. id = vod['lastVIDE']['videoSharedCode']
  854. desc = vod['lastVIDE']['videoTitle']
  855. title = vod['column_name']
  856. url = vod['column_website']
  857. img = vod['column_logo']
  858. year = vod['column_playdate']
  859. brief = vod['column_brief']
  860. actors = ''
  861. if len(url) == 0:
  862. continue
  863. guids = [tid, title, url, img, id, year, actors, brief]
  864. guid = "||".join(guids)
  865. # print(vod_id)
  866. videos.append({
  867. "vod_id": year_prefix + '$$$' + guid if year_prefix else guid,
  868. "vod_name": title,
  869. "vod_pic": img,
  870. "vod_remarks": desc.split('》')[1].strip() if '》' in desc else desc.strip()
  871. })
  872. # print(videos)
  873. return videos
  874. # 分类取结果
  875. def get_list(self, html, tid):
  876. jRoot = json.loads(html)
  877. videos = []
  878. data = jRoot['data']
  879. if data is None:
  880. return []
  881. jsonList = data['list']
  882. for vod in jsonList:
  883. url = vod['url']
  884. title = vod['title']
  885. img = vod['image']
  886. id = vod['id']
  887. try:
  888. brief = vod['brief']
  889. except:
  890. brief = ''
  891. try:
  892. year = vod['year']
  893. except:
  894. year = ''
  895. try:
  896. actors = vod['actors']
  897. except:
  898. actors = ''
  899. if len(url) == 0:
  900. continue
  901. guids = [tid, title, url, img, id, year, actors, brief]
  902. guid = "||".join(guids)
  903. # print(vod_id)
  904. videos.append({
  905. "vod_id": guid,
  906. "vod_name": title,
  907. "vod_pic": img,
  908. "vod_remarks": ''
  909. })
  910. return videos
  911. # 4k分类取结果
  912. def get_list_4k(self, html, tid):
  913. jRoot = json.loads(html)
  914. videos = []
  915. data = jRoot['data']
  916. if data is None:
  917. return []
  918. jsonList = data['list']
  919. for vod in jsonList:
  920. vod_remarks = vod['title']
  921. id = vod['id']
  922. vod = vod['last_video']
  923. img = vod['image']
  924. url = vod['url']
  925. title = vod['title']
  926. brief = vod.get('brief') or ''
  927. year = vod.get('year') or ''
  928. actors = vod.get('actors') or ''
  929. if len(url) == 0:
  930. continue
  931. guids = [tid, title, url, img, id, year, actors, brief]
  932. guid = "||".join(guids)
  933. # print(vod_id)
  934. videos.append({
  935. "vod_id": guid,
  936. "vod_name": title,
  937. "vod_pic": img,
  938. "vod_remarks": vod_remarks
  939. })
  940. return videos
  941. if __name__ == '__main__':
  942. spider = Spider()
  943. spider.init()
  944. spider.init_api_ext_file()
  945. # print(spider.homeContent(True))
  946. # print(spider.homeVideoContent())
  947. # spider.init_api_ext_file()
  948. # url = 'https://api.cntv.cn/lanmu/columnSearch?&fl=&fc=%E6%96%B0%E9%97%BB&cid=&p=1&n=20&serviceId=tvcctv&t=jsonp&cb=Callback'
  949. # url = 'https://api.cntv.cn/lanmu/columnSearch?&fl=&fc=&cid=&p=1&n=20&serviceId=tvcctv&t=json&cb=ko'
  950. # r = spider.fetch(url)
  951. # print(r.text)
  952. # home_content = spider.homeContent(None)
  953. # print(home_content)
  954. cate_content = spider.categoryContent('栏目大全', 1, {'cid': 'n'}, {})
  955. # cate_content = spider.categoryContent('频道直播', 1, None, None)
  956. print(cate_content)
  957. vid = cate_content['list'][0]['vod_id']
  958. print(vid)
  959. detail_content = spider.detailContent([vid])
  960. print(detail_content)
  961. # #
  962. vod_play_from = detail_content['list'][0]['vod_play_from']
  963. vod_play_url = detail_content['list'][0]['vod_play_url']
  964. print(vod_play_from, vod_play_url)
  965. _url = vod_play_url.split('#')[0].split('$')[1]
  966. print(_url)
  967. print('vod_play_from:', vod_play_from, ' vod_play_url:', _url)
  968. play = spider.playerContent(vod_play_from, _url, None)
  969. print(play)
  970. # play = spider.playerContent('道长在线直播', 'cctv1||https://tv.cctv.com/live/cctv1/', None)
  971. # print(play)