Discord.py Google搜索返回无关内容,请求排查原因
问题解决:Discord机器人搜索返回无关内容
问题原因
你用的search函数默认会返回全类型搜索结果(包括图片、视频等),而且直接输出原始结果对象,没做筛选和格式化,所以会出现无关内容。
修改后的代码
from googlesearch import search, SearchResult @bot.command(name='what_is') async def what_is(ctx, *, query): # 要中文搜索可改成:f'什么是 {query}' search_query = f'What is {query}' try: # 过滤非标准网页,指定搜索语言和域名 results = list(search( search_query, num=1, stop=1, pause=2, tld="com", lang="en", # 中文搜索改为"zh-CN" only_standard=True # 仅保留普通网页结果 )) if results: # 提取标题和链接,避免返回无关元数据 result: SearchResult = results[0] await ctx.send(f"查询结果:\n标题:{result.title}\n链接:{result.link}") else: await ctx.send("抱歉,没找到相关信息。") except Exception as e: print(e) await ctx.send("搜索时出现错误。")
关键调整说明
only_standard=True:过滤掉图片、视频等非网页结果,只保留常规网页- 提取
title和link:直接输出结果对象会包含多余内部数据,提取指定字段能保证内容精准 - 语言/域名适配:如果需要中文搜索,把
lang设为"zh-CN"、tld设为"cn",同时将查询语句改为中文格式
内容的提问来源于stack exchange,提问作者RetrebutionMk2
相关产品推荐
相关产品推荐

