You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用lyricsgenius调用Genius API获取歌词偶现EmbedShare冗余后缀如何解决

解决方案

该冗余字符串是Genius网页端内嵌分享功能的标识文本,lyricsgenius通过网页抓取获取歌词时,会因页面结构临时调整、解析规则匹配疏漏误将这段文本带入歌词结果,因此会出现同一首歌返回结果不稳定的情况。

修复方法

1. 手动清理冗余后缀(优先推荐,兼容性最强)

直接对返回的歌词做后置匹配处理,同时补充歌曲搜索结果为空的异常判断,避免程序崩溃。修改后的代码如下:

@commands.command(help="Gives the lyrics of the song XD! format //lyrics (author) (song name)")
async def lyrics(self, ctx, arg1, arg2):
    song = genius.search_song(arg1, arg2)
    # 判空处理,避免搜不到歌时报错
    if not song or not song.lyrics:
        await ctx.send("未查询到对应歌曲的歌词,请确认歌手、歌名拼写正确")
        return
    # 清理冗余后缀
    processed_lyrics = song.lyrics
    redundant_suffix = "EmbedShare URLCopyEmbedCopy"
    # 兼容末尾带换行、不带换行的两种情况
    if processed_lyrics.rstrip().endswith(redundant_suffix):
        processed_lyrics = processed_lyrics.rstrip()[:-len(redundant_suffix)].strip()
    print(processed_lyrics)
    name = ("Lyrics for " + arg2.capitalize() + " by " + arg1.capitalize())
    gembed = discord.Embed(title=name.capitalize(), description=processed_lyrics)
    await ctx.send(embed=gembed)

2. 调整库初始化配置(可与第一种方案叠加做双重兜底)

v3.0及以上版本的lyricsgenius支持开启自动清理冗余内容的配置,初始化Genius实例时添加remove_extra_lyrics=True参数即可:

# 替换你原本初始化genius的代码
genius = lyricsgenius.Genius("你的Genius API密钥", remove_extra_lyrics=True)

内容的提问来源于stack exchange,提问作者Diamondifier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:18:01