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 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
   | import asyncio import aiohttp import json import html import re from pathlib import Path from typing import List, Dict, Any
  class BilibiliFetcher:     def __init__(self):                  self.headers = {             'Cookie': 'SESSDATA=你的SESSDATA内容',             'Origin': 'https://www.bilibili.com',             'Referer': 'https://www.bilibili.com/',             'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'         }         self.session = None         self.uid = None              def encode_html(self, text: str) -> str:         """HTML编码函数,与JavaScript版本保持一致"""         if not isinstance(text, str):             return ''                           text = text.replace('&', '&')         text = text.replace('<', '<')         text = text.replace('>', '>')         text = text.replace('"', '"')                           text = re.sub(r' (?= )|(?<= ) |^ | $', ' ', text, flags=re.MULTILINE)                           text = re.sub(r'\r\n|\r|\n', '<br />', text)                  return text          async def create_session(self):         """创建aiohttp会话"""         self.session = aiohttp.ClientSession(headers=self.headers)          async def close_session(self):         """关闭aiohttp会话"""         if self.session:             await self.session.close()          async def get_user_info(self) -> int:         """获取自己的UID"""         try:             async with self.session.get('https://api.bilibili.com/x/web-interface/nav') as response:                 ujson = await response.json()                              if ujson['code'] != 0:                 print(f'获取用户信息失败: {ujson["message"]}')                 raise Exception(f'获取用户信息失败: {ujson["message"]}')                              self.uid = ujson['data']['mid']             return self.uid                      except Exception as e:             print(f'获取用户信息时出错: {str(e)}')             raise          async def get_followers_page(self, page: int) -> List[Dict[str, Any]]:         """获取指定页的粉丝信息"""         try:             url = f'https://api.bilibili.com/x/relation/fans?vmid={self.uid}&ps=50&pn={page}'             async with self.session.get(url) as response:                 data = await response.json()                              if data['code'] == 0 and data.get('data') and data['data'].get('list'):                 return data['data']['list']             else:                 print(f'获取第{page}页粉丝信息失败: {data.get("message", "未知错误")}')                 return []                          except Exception as e:             print(f'请求第{page}页时出错: {str(e)}')             return []          async def get_all_followers(self, max_pages: int = 20) -> List[Dict[str, Any]]:         """获取所有粉丝信息"""         followers = []                           for i in range(1, max_pages + 1):             page_followers = await self.get_followers_page(i)             if not page_followers:                 break             followers.extend(page_followers)                      return followers          async def get_followers_detail_info(self, followers: List[Dict[str, Any]]) -> None:         """获取所有粉丝的详细信息"""         if not followers:             return                      uids = [str(f['mid']) for f in followers]         uid_str = ','.join(uids)                  try:             url = f'https://api.vc.bilibili.com/x/im/user_infos?uids={uid_str}'             async with self.session.get(url) as response:                 cjson = await response.json()                              if cjson['code'] == 0 and cjson.get('data'):                                  for info in cjson['data']:                     follower = next((f for f in followers if f['mid'] == info['mid']), None)                     if follower:                         follower.update(info)                                  except Exception as e:             print(f'获取粉丝详细信息时出错: {str(e)}')          async def get_followers_stats(self, followers: List[Dict[str, Any]]) -> None:         """获取所有粉丝的粉丝数统计"""         if not followers:             return                               followers_without_stat = [f['mid'] for f in followers]                  while followers_without_stat:             batch = followers_without_stat[:20]             followers_without_stat = followers_without_stat[20:]                          try:                 mids_str = ','.join(map(str, batch))                 url = f'https://api.bilibili.com/x/relation/stats?mids={mids_str}'                 async with self.session.get(url) as response:                     sjson = await response.json()                                      if sjson['code'] == 0 and sjson.get('data'):                                          for mid_str, stat in sjson['data'].items():                         mid = int(mid_str)                         follower = next((f for f in followers if f['mid'] == mid), None)                         if follower:                             follower.update(stat)                                          except Exception as e:                 print(f'获取粉丝统计信息时出错: {str(e)}')          def filter_default_avatars(self, followers: List[Dict[str, Any]]) -> List[Dict[str, Any]]:         """过滤掉使用默认头像的用户"""         filtered = [f for f in followers if '/member/noface.jpg' not in f.get('face', '')]                  print(f'原始粉丝数量: {len(followers)}')         print(f'过滤后粉丝数量: {len(filtered)}')         print(f'已过滤掉 {len(followers) - len(filtered)} 个默认头像用户')                  return filtered          def generate_html(self, followers: List[Dict[str, Any]], output_file: str = 'followers.html') -> None:         """生成HTML文件"""         content = f'''<!DOCTYPE html> <html lang="zh-CN"> <head>   <meta charset="UTF-8">   <meta name="viewport" content="width=device-width, initial-scale=1.0">   <title>粉丝列表</title>   <style>     * {{       font-family: Lato, 'PingFang SC', 'Microsoft YaHei', sans-serif;       font-size: 20px;       overflow-wrap: anywhere;       text-align: justify;       margin: 0;       padding: 0;       box-sizing: border-box;     }}
      body {{       background: #f5f7fa;       padding: 20px;       line-height: 1.6;       min-height: 100vh;     }}
      .container {{       width: 100%;       max-width: none;     }}
      .header {{       text-align: center;       margin-bottom: 30px;     }}
      .header h1 {{       font-size: 32px;       font-weight: 600;       color: #1f2937;       margin-bottom: 8px;     }}
      .header p {{       font-size: 16px;       color: #6b7280;     }}
      .followers-content {{       background: white;       border-radius: 12px;       padding: 20px;       box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);       width: 100%;     }}
      div.inline-block {{       display: inline-block;       margin-right: 5px;       margin-bottom: 10px;     }}
      div.info {{       align-items: center;       display: flex;     }}
      div.image-wrap {{       margin-right: 5px;       position: relative;     }}
      img {{       vertical-align: middle;     }}
      img.face {{       border-radius: 50%;       height: 60px;     }}
      img.icon-face-nft {{       border: 2px solid var(--background-color);       box-sizing: border-box;     }}
      div.image-wrap.has-frame img.face {{       height: 51px;       padding: 19.5px;     }}
      div.image-wrap.has-frame img.face-frame {{       height: 90px;       left: calc(50% - 45px);       position: absolute;       top: 0;     }}
      div.image-wrap img.face-icon {{       border-radius: 50%;       height: 18px;       left: calc(50% + 13.25px);       position: absolute;       top: calc(50% + 13.25px);     }}
      div.image-wrap img.face-icon.second {{       left: calc(50% - 3.75px);     }}
      div.image-wrap.has-frame img.face-icon {{       left: calc(50% + 9px);       top: calc(50% + 9px);     }}
      div.image-wrap.has-frame img.face-icon.second {{       left: calc(50% - 8px);     }}
      @media (max-width: 768px) {{       body {{         padding: 10px;       }}
        .header h1 {{         font-size: 24px;       }}
        .followers-content {{         padding: 15px;       }}
        * {{         font-size: 18px;       }}
        img.face {{         height: 50px;       }}     }}
      @media (max-width: 480px) {{       body {{         padding: 5px;       }}
        .followers-content {{         padding: 10px;       }}
        * {{         font-size: 16px;       }}
        img.face {{         height: 40px;       }}     }}   </style> </head> <body>   <div class="container">     <div class="header">       <h1>粉丝列表</h1>       <p>共 {len(followers)} 位粉丝(已过滤默认头像用户)</p>     </div>
      <div class="followers-content">       {''.join([f'<div class="inline-block"><div class="info"><div class="image-wrap"><img class="face" src="{f.get("face", "")}" referrerpolicy="no-referrer" /></div> <div><strong>{self.encode_html(f.get("name") or f.get("uname", ""))}</strong></div></div></div>' for f in followers])}     </div>   </div> </body> </html>'''
                   with open(output_file, 'w', encoding='utf-8') as f:             f.write(content)                      print(f'成功生成粉丝列表HTML文件,共包含 {len(followers)} 个粉丝')
  async def main():     """主函数"""     fetcher = BilibiliFetcher()          try:                  await fetcher.create_session()                           await fetcher.get_user_info()                           followers = await fetcher.get_all_followers(max_pages=20)                           await fetcher.get_followers_detail_info(followers)                           await fetcher.get_followers_stats(followers)                           filtered_followers = fetcher.filter_default_avatars(followers)                           fetcher.generate_html(filtered_followers, 'followers.html')              except Exception as e:         print(f'程序运行出错: {str(e)}')         return 1              finally:                  await fetcher.close_session()          return 0
  if __name__ == "__main__":     try:         exit_code = asyncio.run(main())         exit(exit_code)     except KeyboardInterrupt:         print("\n程序被用户中断")         exit(1)     except Exception as error:         print(f'程序运行出错: {str(error)}')         exit(1)
 
  |