枯燥了每天呆在学校的生活?接触不到最新的知识?下面将介绍如何在CI上使用PyExecutor组件实现显示最新哔哩哔哩热搜,所有同学只要抬起头来就能了解最新时事喵!ヾ(≧▽≦*)o
前置条件
- 您的电脑装有ClassIsland
- ClassIsland中安装了PyExecutor插件
- 电脑中装有Python
实现方法
在PyExecutor组件设置中输入以下代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
仅使用 Python 标准库获取哔哩哔哩热搜 TOP10 并在 main() 返回指定格式的字符串。
注意:网络请求有可能因为接口变更、IP/UA/Referer 限制或网络不可达而失败。
"""
import urllib.request
import json
import datetime
import io
import gzip
from typing import List
HOT_URL = "https://app.bilibili.com/x/v2/search/trending/ranking"
def fetch_hot_keywords(url: str = HOT_URL, timeout: float = 10.0) -> List[str]:
"""
从 B 站热搜接口拉取关键词列表(尽量返回按 position 排序的 keyword 列表)。
仅使用标准库 urllib。
"""
headers = {
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
"Accept-Encoding": "gzip",
"Referer": "https://www.bilibili.com"
}
req = urllib.request.Request(url, headers=headers, method="GET")
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read()
# 如果返回 gzip 压缩,则解压
encoding = resp.getheader("Content-Encoding", "")
if "gzip" in encoding:
with gzip.GzipFile(fileobj=io.BytesIO(raw)) as gz:
text = gz.read().decode("utf-8", errors="ignore")
else:
text = raw.decode("utf-8", errors="ignore")
data = json.loads(text)
# data 结构按常见实现:data['list'] 每项含 'position' 和 'keyword'
items = data.get("data", {}).get("list", [])
# 过滤并按 position 排序
cleaned = []
for it in items:
# 可能的字段名: 'keyword' 或 'word' 等,做兼容
kw = it.get("keyword") or it.get("word") or it.get("title") or ""
pos = it.get("position")
try:
pos = int(pos) if pos is not None else None
except Exception:
pos = None
if kw:
cleaned.append((pos if pos is not None else 9999, str(kw)))
cleaned.sort(key=lambda x: x[0])
return [kw for _, kw in cleaned]
def format_result(keywords: List[str]) -> str:
"""
把关键词列表格式化为:
哔哩哔哩热搜TOP10(YYYY年MM月DD日HH时MM分SS秒):#1:~|#2:~|...
只显示最多前 10 条。
"""
now = datetime.datetime.now()
ts = now.strftime("%Y年%m月%d日%H时%M分%S秒")
top = keywords[:10]
parts = []
for i, k in enumerate(top, start=1):
# 清理字符串:移除零宽空格等不可打印/特殊Unicode字符
# 只保留常见的可打印字符(汉字、字母、数字、标点等)
cleaned_k = ''.join(char for char in k if not (
# 过滤零宽空格和一些其他不可见字符
ord(char) == 0x200b or # 零宽空格
ord(char) == 0x200c or # 零宽非连接符
ord(char) == 0x200d or # 零宽连接符
ord(char) == 0xfeff or # 零宽不中断空格
0x2000 <= ord(char) <= 0x200F # 各种Unicode空格和不可见字符
))
# 进一步确保没有特殊控制字符
cleaned_k = ''.join(char for char in cleaned_k if char.isprintable() or char.isspace())
parts.append(f"#{i}:{cleaned_k}")
body = "|".join(parts)
return f"哔哩哔哩热搜TOP10({ts}):{body}"
def main() -> str:
"""
返回指定格式的字符串(或在无法获取时返回错误提示)。
"""
try:
kws = fetch_hot_keywords()
if not kws:
return "无法获取哔哩哔哩热搜:返回结果为空或格式不符。"
return format_result(kws)
except Exception as e:
# 不抛异常,返回可读的错误提示(便于在需要时展示)
return f"无法获取哔哩哔哩热搜:{e}"
建议搭配滚动组件一起使用,并设置在上课时隐藏。
效果截图

声明
本方法使用了AI生成,不保证今后一直生效,也不保证在所有设备上均能使用喵。
我怎么能如此优秀(水母语)