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

如何实现Python简易聊天机器人的谷歌搜索结果文本返回功能

实现带谷歌搜索功能的Python简易聊天机器人

要实现能执行谷歌搜索并返回精准文本结果的聊天机器人,可按以下步骤操作:

1. 安装依赖库

使用googlesearch-python库(封装了谷歌搜索接口,无需处理复杂反爬逻辑):

pip install googlesearch-python

2. 核心搜索实现

编写函数调用谷歌搜索,提取最相关结果的关键信息:

from googlesearch import search

def google_search(query, num_results=1):
    # 执行搜索,获取带摘要的结果
    results = list(search(query, num_results=num_results, advanced=True))
    if not results:
        return "抱歉,未找到相关结果。"
    # 返回第一个结果的摘要内容
    return results[0].description

3. 聊天机器人主逻辑

搭建简单的交互循环,接收用户输入并返回搜索结果:

def chatbot():
    print("简易搜索聊天机器人,输入'退出'结束对话")
    while True:
        user_input = input("你:")
        if user_input.lower() == "退出":
            print("机器人:再见!")
            break
        response = google_search(user_input)
        print(f"机器人:{response}")

if __name__ == "__main__":
    chatbot()

4. 优化精准度(可选)

如果需要像示例那样返回更精准的结构化数据(比如埃菲尔铁塔高度),可以结合BeautifulSoup爬取搜索结果页面的具体信息:

from bs4 import BeautifulSoup
import requests

def extract_precise_answer(url):
    try:
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'html.parser')
        # 针对维基百科类页面的信息框提取数据
        infobox = soup.find(class_="infobox")
        if infobox:
            for row in infobox.find_all("tr"):
                if "高度" in row.text:
                    return row.find("td").text.strip()
        return ""
    except Exception:
        return ""

# 修改搜索函数,优先返回精准数据
def google_search(query, num_results=1):
    results = list(search(query, num_results=num_results, advanced=True))
    if not results:
        return "抱歉,未找到相关结果。"
    precise_answer = extract_precise_answer(results[0].url)
    return precise_answer if precise_answer else results[0].description

调整后,当用户提问“埃菲尔铁塔的高度是多少”时,会优先从维基百科信息框中提取到“300米,含顶端天线高330米”这类精准结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:42:10