脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 基于python对B站收藏夹按照视频发布时间进行排序的问题

基于python对B站收藏夹按照视频发布时间进行排序的问题

2021-10-29 09:47Chant_Mee Python

这篇文章主要介绍了基于python对B站收藏夹按照视频发布时间进行排序,在实现过程中中间程序可能因为各种原因挂掉,因此在中间加入了储存中间状态的功能,否则每次挂掉都要重新爬速度非常慢,本文给大家介绍具体使用方法,一

前言

在最一开始,我的B站收藏一直是存放在默认收藏夹中,但是随着视频收藏的越来越多,没有分类的视频放在一起,想在众多视频中找到想要的视频非常困难,因此就对收藏夹里面的视频进行了分类。但是分类之后紧接着又出现了一个新的问题:原来存放在默认收藏夹里面视频的相对顺序被打乱了——明明前几天刚收藏的视频却要翻很多很多页才能找到,因此有了这个程序。

程序的作用

因为我们看到的视频大部分都是通过推荐得到的,而推荐的视频大部分都是刚发布不久,因此大部分收藏的视频的顺序也基本是按照视频发布的顺序来的。那么通过程序对收藏夹中的视频按照发布时间重新排序,那么就和我们收藏视频的顺序几乎一致了。

机理

利用b站的API获取收藏夹中视频的视频的编号,用python中的request库获得视频对应网页的html,之后利用正则表达式得到视频发布的时间。将发布时间和视频的编号绑定,按照视频发布时间从小到大排序,再次利用b站的API将视频收藏到指定收藏夹。

出现的问题

b站视频的av号在八位以下的时候是按照视频发布顺序编排的,但是当到达九位的时候就不是按照发布顺序编排的了,因此只能通过访问视频主页来得到视频发布时间。

b站的API如果长时间比较高频率的访问会出现错误码,因此每次调用API之后都sleep了一下。

中间程序可能因为各种原因挂掉,因此在中间加入了储存中间状态的功能,否则每次挂掉都要重新爬速度非常慢。

使用方法

在创建Sort类对象时,将userAgent,cookie,fid,toFid,csrf传入类的构造函数中,之后调用类中的sortVideos()方法即可完成排序。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
import requests, json, time, re, datetime, random
 
class WriteLog(object):
    def __getCurrentTime(self):
        return str(time.ctime(time.time()))
 
    def writeFile(self, fileName, l):
        with open(self.__getCurrentTime() + fileName, 'w') as f:
            for i in l:
                f.write(str(i) + '\n')
 
class Sort(WriteLog):
    def __init__(self, fid, toFid, csrf, userAgent, cookie, MinSleepTime=5, MaxSleepTime=10):
        self.MinSleepTime = MinSleepTime
        self.MaxSleepTime = MaxSleepTime
        self.fid = str(fid)
        self.toFid = str(toFid)
        self.csrf = csrf
        self.DeadVideo = []
        self.headers = {'User-Agent': userAgent, 'cookie': cookie}
 
    def __Sleep(self):
        sleepTime = random.randint(self.MinSleepTime, self.MaxSleepTime)
        time.sleep(sleepTime)
 
    def __getAllVideoId(self):
        print('Start get all video ID')
        fid = self.fid
        res = []
        cnt = 0
        for i in range(100):
            if i == 0:
                continue
            url = 'https://api.bilibili.com/x/v3/fav/resource/list?media_id=' + fid + '&pn=' + str(i) + '&ps=20&keyword=&order=mtime&type=0&tid=0&platform=web&jsonp=jsonp'
            html = requests.get(url=url, headers=self.headers)
            te = json.loads(html.text)
            te = te['data']['medias']
            if te != None:
                for j in te:
                    res.append(j['id'])
                    print('num: ', cnt, '\tvideoID: ', j['id'])
                    cnt = cnt + 1
                self.__Sleep()
            else:
                break
        print('Finish get all video ID, in total %d' % (len(res)))
        return res
 
    def __addVideoToFavorite(self, vid):
        fid = self.toFid
        csrf = self.csrf
        url = 'https://api.bilibili.com/x/v3/fav/resource/deal'
        data = {
            'rid': vid,
            'type': '2',
            'add_media_ids': fid,
            'del_media_ids': '',
            'jsonp': 'jsonp',
            'csrf': csrf,
            'platform': 'web',
        }
        requests.post(url=url, data=data, headers=self.headers)
        print('finish add video %s to folder %s' % (vid, fid))
 
    def __getVideoPostTime(self, vid):
        vid = str(vid)
        url = 'https://www.bilibili.com/video/av' + vid
        text = requests.get(url).text
        '''
        data-vue-meta="true" itemprop="uploadDate" content="2021-04-07 23:29:21"><meta data-vue-meta="true" itemprop="datePublished" c
        '''
        reg = re.compile('content="([0-9]+)-([0-9]+)-([0-9]+)\s([0-9]+):([0-9]+):([0-9]+)"')
        text = reg.findall(text)
        if len(text) == 0:
            return -1
        text = text[0]
        if len(text) < 6:
            return -1
        t = ""
        for i in text:
            t = t + str(i)
        print('finish get video %s post time, it\'s post time is: %s' % (vid, t))
        return int(t)
 
    def __Unique(self, l):
        size = len(l)
        if size == 0:
            return []
        res = [l[0]]
        for i in range(size):
            if i == 0:
                continue
            if l[i] != l[i - 1]:
                res.append(l[i])
        return res
 
    def __addVideo(self, res):
        cnt = 0
        for i in res:
            self.__addVideoToFavorite(vid=i)
            self.__Sleep()
            cnt = cnt + 1
 
    def __getVideosTime(self, res):
        videos = []
        cnt = 0
        for i in res:
            t = self.__getVideoPostTime(i)
            if t == -1:
                continue
            item = {
                'vid': str(i),
                'postTime': t
            }
            videos.append(item)
            cnt = cnt + 1
        return videos
 
    def sortVideos(self):
        fid = self.fid
        toFid = self.toFid
        res = self.__getAllVideoId()
        self.writeFile('getAllVideoId' + fid + 'to' + toFid, res)
        videos = self.__getVideosTime(res)
        videos = sorted(videos, key=lambda x: x['postTime'])
        res = []
        for i in videos:
            res.append(i['vid'])
        res = self.__Unique(res)
        self.writeFile('getVideosTime' + fid + 'to' + toFid, res)
        self.__addVideo(res)
        self.writeFile('err' + fid + 'to' + toFid, self.DeadVideo)
 
if __name__=='__main__':
    userAgent = ''
    cookie = ''
    fid = ''
    toFid = ''
    csrf = ''
    sortVideo = Sort(fid=fid, toFid=toFid, csrf=csrf, userAgent=userAgent, cookie=cookie)
    sortVideo.sortVideos()

以上就是基于python对B站收藏夹按照视频发布时间进行排序的问题的详细内容,更多关于python视频发布时间排序的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/chantmee/p/14761690.html

延伸 · 阅读

精彩推荐