py_bilimd.py 18.2 KB
Newer Older
1 2
# coding=utf-8
# !/usr/bin/python
H
hjdhnx 已提交
3
import sys
4

H
hjdhnx 已提交
5 6 7 8 9 10 11 12
sys.path.append('..')
from base.spider import Spider
import json
from requests import session, utils
import os
import time
import base64

13

H
hjdhnx 已提交
14
class Spider(Spider):  # 元类 默认的元类 type
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    def getName(self):
        return "哔哩影视"

    def init(self, extend=""):
        print("============{0}============".format(extend))
        pass

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def homeContent(self, filter):
        result = {}
        cateManual = {
            "番剧": "1",
            "国创": "4",
            "电影": "2",
            "电视剧": "5",
            "纪录片": "3",
            "综艺": "7",
            "全部": "全部",
            "追番": "追番",
            "追剧": "追剧",
            "时间表": "时间表",

        }
        classes = []
        for k in cateManual:
            classes.append({
                'type_name': k,
                'type_id': cateManual[k]
            })
        result['class'] = classes
        if (filter):
            result['filters'] = self.config['filter']
        return result

    cookies = ''
    userid = ''

    def getCookie(self):
        # --------↓↓↓↓↓↓↓------在下方cookies_str后的双引号内填写-------↓↓↓↓↓↓↓--------
        cookies_str = ""
        if cookies_str:
            cookies = dict([co.strip().split('=', 1) for co in cookies_str.split(';')])
            bili_jct = cookies['bili_jct']
            SESSDATA = cookies['SESSDATA']
            DedeUserID = cookies['DedeUserID']
            cookies_jar = {"bili_jct": bili_jct,
                           'SESSDATA': SESSDATA,
                           'DedeUserID': DedeUserID
                           }
            rsp = session()
            rsp.cookies = cookies_jar
            content = self.fetch("https://api.bilibili.com/x/web-interface/nav", cookies=rsp.cookies)
            res = json.loads(content.text)
            if res["code"] == 0:
                self.cookies = rsp.cookies
                self.userid = res["data"].get('mid')
                return rsp.cookies
        rsp = self.fetch("https://www.bilibili.com/")
        self.cookies = rsp.cookies
        return rsp.cookies

    # 将超过10000的数字换成成以万和亿为单位
    def zh(self, num):
        if int(num) >= 100000000:
            p = round(float(num) / float(100000000), 1)
            p = str(p) + '亿'
        else:
            if int(num) >= 10000:
                p = round(float(num) / float(10000), 1)
                p = str(p) + '万'
            else:
                p = str(num)
        return p

    def homeVideoContent(self):
        result = {}
        videos = self.get_rank(1)['list'][0:5]
        for i in [4, 2, 5, 3, 7]:
            videos += self.get_rank2(i)['list'][0:5]
        result['list'] = videos
        return result

    def get_rank(self, tid):
        result = {}
        url = 'https://api.bilibili.com/pgc/web/rank/list?season_type={0}&day=3'.format(tid)
        rsp = self.fetch(url, cookies=self.cookies)
        content = rsp.text
        jo = json.loads(content)
        if jo['code'] == 0:
            videos = []
            vodList = jo['result']['list']
            for vod in vodList:
                aid = str(vod['season_id']).strip()
                title = vod['title'].strip()
                img = vod['cover'].strip()
                remark = vod['new_ep']['index_show']
                videos.append({
                    "vod_id": aid,
                    "vod_name": title,
                    "vod_pic": img,
                    "vod_remarks": remark
                })
            result['list'] = videos
            result['page'] = 1
            result['pagecount'] = 1
            result['limit'] = 90
            result['total'] = 999999
        return result

    def get_rank2(self, tid):
        result = {}
        url = 'https://api.bilibili.com/pgc/season/rank/web/list?season_type={0}&day=3'.format(tid)
        rsp = self.fetch(url, cookies=self.cookies)
        content = rsp.text
        jo = json.loads(content)
        if jo['code'] == 0:
            videos = []
            vodList = jo['data']['list']
            for vod in vodList:
                aid = str(vod['season_id']).strip()
                title = vod['title'].strip()
                img = vod['cover'].strip()
                remark = vod['new_ep']['index_show']
                videos.append({
                    "vod_id": aid,
                    "vod_name": title,
                    "vod_pic": img,
                    "vod_remarks": remark
                })
            result['list'] = videos
            result['page'] = 1
            result['pagecount'] = 1
            result['limit'] = 90
            result['total'] = 999999
        return result

    def get_zhui(self, pg, mode):
        result = {}
        if len(self.cookies) <= 0:
            self.getCookie()
        url = 'https://api.bilibili.com/x/space/bangumi/follow/list?type={2}&follow_status=0&pn={1}&ps=10&vmid={0}'.format(self.userid, pg, mode)
        rsp = self.fetch(url, cookies=self.cookies)
        content = rsp.text
        jo = json.loads(content)
        videos = []
        vodList = jo['data']['list']
        for vod in vodList:
            aid = str(vod['season_id']).strip()
            title = vod['title']
            img = vod['cover'].strip()
            remark = vod['new_ep']['index_show'].strip()
            videos.append({
                "vod_id": aid,
                "vod_name": title,
                "vod_pic": img,
                "vod_remarks": remark
            })
        result['list'] = videos
        result['page'] = pg
        result['pagecount'] = 9999
        result['limit'] = 90
        result['total'] = 999999
        return result

    def get_all(self, tid, pg, order, season_status, extend):
        result = {}
        if len(self.cookies) <= 0:
            self.getCookie()
        url = 'https://api.bilibili.com/pgc/season/index/result?order={2}&pagesize=20&type=1&season_type={0}&page={1}&season_status={3}'.format(tid, pg, order, season_status)
        rsp = self.fetch(url, cookies=self.cookies)
        content = rsp.text
        jo = json.loads(content)
        videos = []
        vodList = jo['data']['list']
        for vod in vodList:
            aid = str(vod['season_id']).strip()
            title = vod['title']
            img = vod['cover'].strip()
            remark = vod['index_show'].strip()
            videos.append({
                "vod_id": aid,
                "vod_name": title,
                "vod_pic": img,
                "vod_remarks": remark
            })
        result['list'] = videos
        result['page'] = pg
        result['pagecount'] = 9999
        result['limit'] = 90
        result['total'] = 999999
        return result

    def get_timeline(self, tid, pg):
        result = {}
        url = 'https://api.bilibili.com/pgc/web/timeline/v2?season_type={0}&day_before=2&day_after=4'.format(tid)
        rsp = self.fetch(url, cookies=self.cookies)
        content = rsp.text
        jo = json.loads(content)
        if jo['code'] == 0:
            videos1 = []
            vodList = jo['result']['latest']
            for vod in vodList:
                aid = str(vod['season_id']).strip()
                title = vod['title'].strip()
                img = vod['cover'].strip()
                remark = vod['pub_index'] + ' ' + vod['follows'].replace('系列', '')
                videos1.append({
                    "vod_id": aid,
                    "vod_name": title,
                    "vod_pic": img,
                    "vod_remarks": remark
                })
            videos2 = []
            for i in range(0, 7):
                vodList = jo['result']['timeline'][i]['episodes']
                for vod in vodList:
                    if str(vod['published']) == "0":
                        aid = str(vod['season_id']).strip()
                        title = str(vod['title']).strip()
                        img = str(vod['cover']).strip()
                        date = str(time.strftime("%m-%d %H:%M", time.localtime(vod['pub_ts'])))
                        remark = date + "   " + vod['pub_index']
                        videos2.append({
                            "vod_id": aid,
                            "vod_name": title,
                            "vod_pic": img,
                            "vod_remarks": remark
                        })
            result['list'] = videos2 + videos1
            result['page'] = 1
            result['pagecount'] = 1
            result['limit'] = 90
            result['total'] = 999999
        return result

    def categoryContent(self, tid, pg, filter, extend):
        result = {}
        if len(self.cookies) <= 0:
            self.getCookie()
        if tid == "1":
            return self.get_rank(tid=tid)
        elif tid in {"2", "3", "4", "5", "7"}:
            return self.get_rank2(tid=tid)
        elif tid == "全部":
            tid = '1'    # 全部界面默认展示最多播放的番剧
            order = '2'
            season_status = '-1'
            if 'tid' in extend:
                tid = extend['tid']
            if 'order' in extend:
                order = extend['order']
            if 'season_status' in extend:
                season_status = extend['season_status']
            return self.get_all(tid, pg, order, season_status, extend)
        elif tid == "追番":
            return self.get_zhui(pg, 1)
        elif tid == "追剧":
            return self.get_zhui(pg, 2)
        elif tid == "时间表":
            tid = 1
            if 'tid' in extend:
                tid = extend['tid']
            return self.get_timeline(tid, pg)
        else:
            result = self.searchContent(key=tid,  quick="false")
        return result

    def cleanSpace(self, str):
        return str.replace('\n', '').replace('\t', '').replace('\r', '').replace(' ', '')

    def detailContent(self, array):
        aid = array[0]
        url = "https://api.bilibili.com/pgc/view/web/season?season_id={0}".format(aid)
        rsp = self.fetch(url, headers=self.header)
        jRoot = json.loads(rsp.text)
        jo = jRoot['result']
        id = jo['season_id']
        title = jo['title']
        pic = jo['cover']
        # areas = jo['areas']['name']  改bilidanmu显示弹幕
        typeName = jo['share_sub_title']
        date = jo['publish']['pub_time'][0:4]
        dec = jo['evaluate']
        remark = jo['new_ep']['desc']
        stat = jo['stat']
        # 演员和导演框展示视频状态,包括以下内容:
        status = "弹幕: " + self.zh(stat['danmakus']) + " 点赞: " + self.zh(stat['likes']) + " 投币: " + self.zh(
            stat['coins']) + " 追番追剧: " + self.zh(stat['favorites'])
        if 'rating' in jo:
            score = "评分: " + str(jo['rating']['score']) + ' ' + jo['subtitle']
        else:
            score = "暂无评分" + ' ' + jo['subtitle']
        vod = {
            "vod_id": id,
            "vod_name": title,
            "vod_pic": pic,
            "type_name": typeName,
            "vod_year": date,
            "vod_area": "bilidanmu",
            "vod_remarks": remark,
            "vod_actor": status,
            "vod_director": score,
            "vod_content": dec
        }
        ja = jo['episodes']
        playUrl = ''
        for tmpJo in ja:
            eid = tmpJo['id']
            cid = tmpJo['cid']
            part = tmpJo['title'].replace("#", "-")
            playUrl = playUrl + '{0}${1}_{2}#'.format(part, eid, cid)

        vod['vod_play_from'] = 'B站'
        vod['vod_play_url'] = playUrl

        result = {
            'list': [
                vod
            ]
        }
        return result

    def searchContent(self, key, quick):
        if len(self.cookies) <= 0:
            self.getCookie()
        url1 = 'https://api.bilibili.com/x/web-interface/search/type?search_type=media_bangumi&keyword={0}'.format(
            key)  # 番剧搜索
        rsp1 = self.fetch(url1, cookies=self.cookies)
        content1 = rsp1.text
        jo1 = json.loads(content1)
        rs1 = jo1['data']
        url2 = 'https://api.bilibili.com/x/web-interface/search/type?search_type=media_ft&keyword={0}'.format(
            key)  # 影视搜索
        rsp2 = self.fetch(url2, cookies=self.cookies)
        content2 = rsp2.text
        jo2 = json.loads(content2)
        rs2 = jo2['data']
        videos = []
        if rs1['numResults'] == 0:
            vodList = jo2['data']['result']
        elif rs2['numResults'] == 0:
            vodList = jo1['data']['result']
        else:
            vodList = jo1['data']['result'] + jo2['data']['result']
        for vod in vodList:
            aid = str(vod['season_id']).strip()
            title = key + '➢' + vod['title'].strip().replace("<em class=\"keyword\">", "").replace("</em>", "")
            img = vod['cover'].strip()  # vod['eps'][0]['cover'].strip()原来的错误写法
            remark = vod['index_show']
            videos.append({
                "vod_id": aid,
                "vod_name": title,
                "vod_pic": img,
                "vod_remarks": remark
            })
        result = {
            'list': videos
        }
        return result

    def playerContent(self, flag, id, vipFlags):
        result = {}
        ids = id.split("_")
        header = {
            "Referer": "https://www.bilibili.com",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36"
        }
        url = 'https://api.bilibili.com/pgc/player/web/playurl?qn=116&ep_id={0}&cid={1}'.format(ids[0], ids[1])
        if len(self.cookies) <= 0:
            self.getCookie()
        rsp = self.fetch(url, cookies=self.cookies, headers=header)
        jRoot = json.loads(rsp.text)
        if jRoot['message'] != 'success':
            print("需要大会员权限才能观看")
            return {}
        jo = jRoot['result']
        ja = jo['durl']
        maxSize = -1
        position = -1
        for i in range(len(ja)):
            tmpJo = ja[i]
            if maxSize < int(tmpJo['size']):
                maxSize = int(tmpJo['size'])
                position = i

        url = ''
        if len(ja) > 0:
            if position == -1:
                position = 0
            url = ja[position]['url']

        result["parse"] = 0
        result["playUrl"] = ''
        result["url"] = url
        result["header"] = {
            "Referer": "https://www.bilibili.com",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36"
        }
        result["contentType"] = 'video/x-flv'
        return result

    config = {
        "player": {},
        "filter": {
            "全部": [
                {
                    "key": "tid",
                    "name": "分类",
                    "value": [{
                        "n": "番剧",
                        "v": "1"
                    },
                        {
                            "n": "国创",
                            "v": "4"
                        },

                        {
                            "n": "电影",
                            "v": "2"
                        },
                        {
                            "n": "电视剧",
                            "v": "5"
                        },
                        {
                            "n": "记录片",
                            "v": "3"
                        },
                        {
                            "n": "综艺",
                            "v": "7"
                        }

                    ]
                },
                {
                    "key": "order",
                    "name": "排序",
                    "value": [

                        {
                            "n": "播放数量",
                            "v": "2"
                        },

                        {
                            "n": "更新时间",
                            "v": "0"
                        },

                        {
                            "n": "最高评分",
                            "v": "4"
                        },
                        {
                            "n": "弹幕数量",
                            "v": "1"
                        },
                        {
                            "n": "追看人数",
                            "v": "3"
                        },

                        {
                            "n": "开播时间",
                            "v": "5"
                        },
                        {
                            "n": "上映时间",
                            "v": "6"
                        },

                    ]
                },
                {
                    "key": "season_status",
                    "name": "付费",
                    "value": [
                        {
                            "n": "全部",
                            "v": "-1"
                        },
                        {
                            "n": "免费",
                            "v": "1"
                        },

                        {
                            "n": "付费",
                            "v": "2%2C6"
                        },

                        {
                            "n": "大会员",
                            "v": "4%2C6"
                        },

                    ]
                },
            ],


            "时间表": [{
                "key": "tid",
                "name": "分类",
                "value": [

                    {
                        "n": "番剧",
                        "v": "1"
                    },

                    {
                        "n": "国创",
                        "v": "4"
                    },

                ]
            },
            ],
        }
    }


    header = {
        "Referer": "https://www.bilibili.com",
        "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
    }

    def localProxy(self, param):
        return [200, "video/MP2T", action, ""]