Repository: yt-dlp/yt-dlp

Issue:
【bilibili】yt-dlp always downloads the subtitle of the first video when downloads videos with multiple parts from bilibili
### DO NOT REMOVE OR SKIP THE ISSUE TEMPLATE

- [X] I understand that I will be **blocked** if I *intentionally* remove or skip any mandatory\* field

### Checklist

- [X] I'm reporting a broken site
- [X] I've verified that I'm running yt-dlp version **2023.02.17** ([update instructions](https://github.com/yt-dlp/yt-dlp#update)) or later (specify commit)
- [X] I've checked that all provided URLs are playable in a browser with the same IP and same login details
- [X] I've checked that all URLs and arguments with special characters are [properly quoted or escaped](https://github.com/yt-dlp/yt-dlp/wiki/FAQ#video-url-contains-an-ampersand--and-im-getting-some-strange-output-1-2839-or-v-is-not-recognized-as-an-internal-or-external-command)
- [X] I've searched [known issues](https://github.com/yt-dlp/yt-dlp/issues/3766) and the [bugtracker](https://github.com/yt-dlp/yt-dlp/issues?q=) for similar issues **including closed ones**. DO NOT post duplicates
- [X] I've read the [guidelines for opening an issue](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#opening-an-issue)
- [X] I've read about [sharing account credentials](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#are-you-willing-to-share-account-details-if-needed) and I'm willing to share it if required

### Region

China

### Provide a description that is worded well enough to be understood

# Issue
When downloading bilibili videos which have multiple parts and each parts has its own subtitle, yt-dlp always download the first video's subtitle.

e.g.
```
PS C:\Users\lxyan> yt-dlp.exe --version
2023.02.17

yt-dlp.exe --embed-thumbnail --format-sort vcodec:av01 --cookies-from-browser firefox --write-subs --sub-langs ai-zh https://www.bilibili.com/video/BV15v411g7VP
```

Downloaded files:

![图片](https://user-images.githubusercontent.com/15712263/221401206-bbb6a786-d4dc-4357-8b9f-787212ef0244.png)
These subtitle files are all the **same file** (note they all have same size) of the **first video**.

# Reason:
yt-dlp reads bilibili's subtitle info from `window.__INITIAL_STATE__` -> `traverse_obj(initial_state, ('videoData', 'subtitle', 'list'))['subtitle_url']` but I don't know why, each parts of videos on bilibili have the same `subtitle_url` at this place. 

![图片](https://user-images.githubusercontent.com/15712263/221401617-dccc766b-1b2c-4d3f-997f-b8819074b120.png)

# Solution

One possible solution is get `subtitle_url` through bilibili's api.
I have fixed it by modify `yt_dlp\extractor\bilibili.py`:

![图片](https://user-images.githubusercontent.com/15712263/221401397-d4590b8c-885e-4e57-b9ad-bdd2ac79d477.png)


### Provide verbose output that clearly demonstrates the problem

- [X] Run **your** yt-dlp command with **-vU** flag added (`yt-dlp -vU <your command line>`)
- [X] Copy the WHOLE output (starting with `[debug] Command-line config`) and insert it below

### Complete Verbose Output

```shell
PS C:\Users\lxyan> yt-dlp.exe --version
2023.02.17

PS C:\Users\lxyan> yt-dlp.exe -vU --embed-thumbnail --format-sort vcodec:av01 --cookies-from-browser firefox --write-subs --sub-langs ai-zh https://www.bilibili.com/video/BV15v411g7VP?p=2
[debug] Command-line config: ['-vU', '--embed-thumbnail', '--format-sort', 'vcodec:av01', '--cookies-from-browser', 'firefox', '--write-subs', '--sub-langs', 'ai-zh', 'https://www.bilibili.com/video/BV15v411g7VP?p=2']
[debug] Portable config "C:\Users\lxyan\AppData\Scoop\apps\yt-dlp\current\yt-dlp.conf": []
[debug] Encodings: locale cp936, fs utf-8, pref cp936, out utf-8, error utf-8, screen utf-8
[debug] yt-dlp version 2023.02.17 [a0a7c01] (win_exe)
[debug] Python 3.8.10 (CPython AMD64 64bit) - Windows-10-10.0.19045-SP0 (OpenSSL 1.1.1k  25 Mar 2021)
[debug] exe versions: ffmpeg 5.1.2-full_build-www.gyan.dev (setts), ffprobe 5.1.2-full_build-www.gyan.dev
[debug] Optional libraries: Cryptodome-3.17, brotli-1.0.9, certifi-2022.12.07, mutagen-1.46.0, sqlite3-2.6.0, websockets-10.4
[Cookies] Extracting cookies from firefox
[debug] Extracting cookies from: "C:\Users\lxyan\AppData\Roaming\Mozilla\Firefox\Profiles\gukxnd4w.default\cookies.sqlite"
[Cookies] Extracted 990 cookies from firefox
[debug] Proxy map: {'http': 'http://127.0.0.1:7890', 'https': 'https://127.0.0.1:7890', 'ftp': 'ftp://127.0.0.1:7890'}
[debug] Loaded 1782 extractors
[debug] Fetching release info: https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest
ERROR: Unable to obtain version info; Please try again later or Visit  https://github.com/yt-dlp/yt-dlp/releases/latest
[BiliBili] Extracting URL: https://www.bilibili.com/video/BV15v411g7VP?p=2
[BiliBili] 15v411g7VP: Downloading webpage
[BiliBili] BV15v411g7VP: Extracting videos in anthology
[BiliBili] 250927429: Extracting chapters
[BiliBili] BV15v411g7VP: Downloading JSON metadata
[info] BV15v411g7VP_p2: Downloading subtitles: ai-zh
[debug] Sort order given by user: vcodec:av01
[debug] Formats sorted by: hasvid, ie_pref, vcodec:av01(11), lang, quality, res, fps, hdr:12(7), channels, acodec, filesize, fs_approx, tbr, vbr, abr, asr, proto, vext, aext, hasaud, source, id
[debug] Default format spec: bestvideo*+bestaudio/best
[info] BV15v411g7VP_p2: Downloading 1 format(s): 14+2
[info] Writing video subtitles to: 数学分析 陈纪修老师 1080p高清版(全集) p02 2.第1章 第1节 集合（2） [BV15v411g7VP_p2].ai-zh.srt
[info] Downloading video thumbnail 0 ...
[info] Writing video thumbnail 0 to: 数学分析 陈纪修老师 1080p高清版(全集) p02 2.第1章 第1节 集合（2） [BV15v411g7VP_p2].jpg
[debug] Invoking http downloader on "https://xy222x136x90x3xy.mcdn.bilivideo.cn:4483/upgcxcode/49/91/420879149/420879149-1-100026.m4s?e=ig8euxZM2rNcNbdlhoNvNC8BqJIzNbfqXBvEqxTEto8BTrNvN0GvT90W5JZMkX_YN0MvXg8gNEV4NC8xNEV4N03eN0B5tZlqNxTEto8BTrNvNeZVuJ10Kj_g2UB02J0mN0B5tZlqNCNEto8BTrNvNC7MTX502C8f2jmMQJ6mqF2fka1mqx6gqj0eN0B599M=&uipk=5&nbs=1&deadline=1677409834&gen=playurlv2&os=mcdn&oi=620292573&trid=000064440e0f39954b1d8acebf5ca5bee94fu&mid=397105271&platform=pc&upsig=558da1f22ae96e3d210da23aa98a87bb&uparams=e,uipk,nbs,deadline,gen,os,oi,trid,mid,platform&mcdnid=1002589&bvc=vod&nettype=0&orderid=0,3&buvid=06FE81FE-7BF6-A5B5-734C-2952EAC79CF504833infoc&build=0&agrr=1&bw=39577&logo=A0000001"
[debug] File locking is not supported. Proceeding without locking
[download] Destination: 数学分析 陈纪修老师 1080p高清版(全集) p02 2.第1章 第1节 集合（2） [BV15v411g7VP_p2].f14.mp4
[download]   2.0% of   97.91MiB at    3.62MiB/s ETA 00:26
ERROR: Interrupted by user
# (No need to download it. you can already notice the subtitle file belongs to the ?p=1 video instead of the ?p=2 video)
```



Discussion:
I'll make a PR later.

Resolving patch:
diff --git a/yt_dlp/extractor/bilibili.py b/yt_dlp/extractor/bilibili.py
--- a/yt_dlp/extractor/bilibili.py
+++ b/yt_dlp/extractor/bilibili.py
@@ -81,7 +81,7 @@ def json2srt(self, json_data):
                          f'{line["content"]}\n\n')
         return srt_data
 
-    def _get_subtitles(self, video_id, initial_state, cid):
+    def _get_subtitles(self, video_id, aid, cid):
         subtitles = {
             'danmaku': [{
                 'ext': 'xml',
@@ -89,7 +89,8 @@ def _get_subtitles(self, video_id, initial_state, cid):
             }]
         }
 
-        for s in traverse_obj(initial_state, ('videoData', 'subtitle', 'list')) or []:
+        video_info_json = self._download_json(f'https://api.bilibili.com/x/player/v2?aid={aid}&cid={cid}', video_id)
+        for s in traverse_obj(video_info_json, ('data', 'subtitle', 'subtitles', ...)):
             subtitles.setdefault(s['lan'], []).append({
                 'ext': 'srt',
                 'data': self.json2srt(self._download_json(s['subtitle_url'], video_id))
@@ -331,7 +332,7 @@ def _real_extract(self, url):
             'timestamp': traverse_obj(initial_state, ('videoData', 'pubdate')),
             'duration': float_or_none(play_info.get('timelength'), scale=1000),
             'chapters': self._get_chapters(aid, cid),
-            'subtitles': self.extract_subtitles(video_id, initial_state, cid),
+            'subtitles': self.extract_subtitles(video_id, aid, cid),
             '__post_extractor': self.extract_comments(aid),
             'http_headers': {'Referer': url},
         }


Test patch: