使用duckduckgo_search python api 进行免费且不限次数的搜索

该文章已生成可运行项目,

使用duckduckgo_search python api 进行免费且不限次数的搜索

  • 搜索内容
  • 搜索新闻
  • 搜索图片
  • 搜索视频

重要参数

官网参数

region='wt-wt',  # wt-wt、us-en、uk-en、ru-ru 等。默认为“wt-wt”
safesearch='off',  # on, moderate, off. Defaults to "moderate"
timelimit='y',     #  d, w, m, y. Defaults to None
max_results=10  # 最大结果数量

python 代码

from duckduckgo_search import DDGS
from pprint import pprint

with DDGS(
    timeout=20,
    proxies="http://localhost:7890"  # VPN代理
) as ddgs:
    pprint([r for r in ddgs.text("大模型", region='cn-zh', max_results=10)])  # 搜索内容
    # pprint([r for r in ddgs.news("CHATGPT", region='cn-zh', max_results=10)])  # 搜索新闻
    # pprint([r for r in ddgs.images("刘亦菲", region='cn-zh', max_results=10)])  # 搜索图片
    # pprint([r for r in ddgs.videos("搞笑视频", region='cn-zh', max_results=10)])  # 搜索图片


返回体

  • 搜索内容
{
'body': ..., 
'href': ..., 
'title': ....
}
  • 搜索新闻
 {
  'body': '',
  'date': '2025-06-18T09:02:00+00:00',
  'image': '',
  'source': '',
  'title': '',
  'url': 'https://www***************25/0618/26913.html'
  }
  • 搜索图片
 {
  'height': 1928,
  'width': 1296,
  'image': 'https://n.sinaimg.cn/sinakd201********8832682.jpg',
  'source': 'Bing',
  'thumbnail': 'https://tse1.mm.bing.net/th?id=OIP.8T****gHaLB&pid=Api',
  'title': '********全球首映。',
  'url': 'https://k.sin********z.html?from=ent&subch=oent',
  }
  • 搜索视频
{
  'content': 'https://www.youtube.c*******v732WBOg',
  'description': '🎉欢迎************************..',
  'duration': '0:19',
  'embed_html': '<iframe width="1280" height="720" '
                'src="https://ww******732WBOg?autoplay=1" '
                'frameborder="0" allowfullscreen></iframe>',
  'embed_url': 'https://ww**732WBOg?autoplay=1',
  'image_token': 'ba7b4b8ce1c8**8bca1351c81bcc6b4a25e65de2a',
  'images': {'large': 'https://tse2.mm.bin**hOsA1potKn9%2foWFw&pid=Api',
             'medium': 'https://tse2.m**qQhOsA1potKn9%2foWFw&pid=Api',
             'motion': '',
             'small': 'https://tse2**bqQhOsA1potKn9%2foWFw&pid=Api'},
  'provider': 'Bing',
  'published': '2025-06-17**:52.0000000',
  'publisher': 'You**be',
  'statistics': {'viewCount': None},
  'title': '75166****156367.mp4',
  'uploader': '****'}]
  
本文章已经生成可运行项目
#!/usr/bin/env python3 import os import json import requests import readline from datetime import datetime class DeepSeekTerminalChat: def __init__(self, deepseek_api_key, bocha_api_key=None): self.deepseek_api_key = deepseek_api_key self.bocha_api_key = bocha_api_key self.deepseek_api_url = "https://api.deepseek.com/v1/chat/completions" self.bocha_api_url = "https://api.bochaai.com/v1/web-search" self.headers = { "Authorization": f"Bearer {deepseek_api_key}", "Content-Type": "application/json" } self.conversation_history = [] def search_web(self, query, max_results=5): """调用博查Web Search API进行联网搜索[1,2](@ref)""" if not self.bocha_api_key: return None try: payload = { "query": query, "count": max_results, "summary": True, # 开启详细摘要[1,5](@ref) "freshness": "noLimit" } headers = { "Authorization": f"Bearer {self.bocha_api_key}", "Content-Type": "application/json" } response = requests.post(self.bocha_api_url, headers=headers, json=payload, timeout=10) response.raise_for_status() data = response.json() # 解析搜索结果[5](@ref) if "data" in data and "webPages" in data["data"]: web_results = data["data"]["webPages"]["value"] formatted_results = [] for i, item in enumerate(web_results[:max_results]): result_text = f"{i+1}. 【{item.get('name', '无标题')}】\n" result_text += f" 链接: {item.get('url', '无链接')}\n" result_text += f" 摘要: {item.get('snippet', '无摘要')}\n" if 'datePublished' in item: result_text += f" 时间: {item['datePublished']}\n" formatted_results.append(result_text) return "\n".join(formatted_results) except Exception as e: print(f"搜索请求错误: {e}") return None return None def should_search_web(self, user_input): """判断是否需要联网搜索[7](@ref)""" search_keywords = [ '最新', '新闻', '天气', '今天', '现在', '实时', '当前', '最近', '2025', '2024', '怎么样', '如何', '为什么', '是什么', 'update', 'news', 'weather', 'live', 'current' ] user_input_lower = user_input.lower() return any(keyword in user_input_lower for keyword in search_keywords) def send_message_stream(self, message): """发送消息并获取流式响应,自动加入网络搜索结果""" # 判断是否需要联网搜索 web_results = None if self.bocha_api_key and self.should_search_web(message): print("\n🔍 正在联网搜索最新信息...", end="", flush=True) web_results = self.search_web(message) print("完成!\n") # 构建消息上下文 current_context = [] # 添加网络搜索结果到上下文 if web_results: search_context = { "role": "system", "content": f"以下是根据用户问题搜索到的实时网络信息(当前时间:{datetime.now().strftime('%Y-%m-%d %H:%M')}):\n\n{web_results}\n\n请基于这些实时信息回答用户问题,如果信息不足再使用你的知识库。" } current_context.append(search_context) # 添加对话历史 current_context.extend(self.conversation_history) # 添加当前消息 current_context.append({"role": "user", "content": message}) data = { "model": "deepseek-chat", "messages": current_context, "stream": True, "temperature": 0.7 } try: response = requests.post(self.deepseek_api_url, headers=self.headers, json=data, stream=True) response.raise_for_status() full_response = "" print("DeepSeek: ", end="", flush=True) for line in response.iter_lines(): if line: line = line.decode('utf-8') if line.startswith('data: '): data_str = line[6:] if data_str == '[DONE]': break try: data_json = json.loads(data_str) if 'choices' in data_json and len(data_json['choices']) > 0: delta = data_json['choices'][0].get('delta', {}) if 'content' in delta: content = delta['content'] print(content, end="", flush=True) full_response += content except json.JSONDecodeError: continue print() # 更新对话历史 self.conversation_history.append({"role": "user", "content": message}) self.conversation_history.append({"role": "assistant", "content": full_response}) return full_response except requests.exceptions.RequestException as e: return f"请求错误: {e}" except KeyError: return "无法解析API响应" def multiline_input(self): """支持多行输入的函数""" print("请输入多行内容,输入'.'单独一行结束输入:") lines = [] while True: try: line = input() if line == '.': break lines.append(line) except EOFError: break return '\n'.join(lines) def start_chat(self): """启动聊天终端""" print("🤖 DeepSeek 终端聊天工具已启动! (流式输出模式)") print("🌐 联网搜索功能: " + ("已启用" if self.bocha_api_key else "未启用")) print("📝 输入 'quit' 或 'exit' 退出程序") print("📝 输入 '/multiline' 进入多行输入模式") print("📝 输入 '/clear' 清除对话历史") print("📝 输入 '/help' 显示帮助信息") print("📝 输入 '/search 关键词' 手动触发搜索") print("-" * 50) while True: try: user_input = input("你: ").strip() if user_input.lower() in ['quit', 'exit']: print("再见!") break if user_input.lower() == '/multiline': user_input = self.multiline_input() if not user_input: print("输入为空,请重新输入") continue if user_input.lower() == '/clear': self.conversation_history = [] print("对话历史已清除") continue if user_input.lower() == '/help': self.show_help() continue if user_input.startswith('/search ') and self.bocha_api_key: search_query = user_input[8:].strip() if search_query: results = self.search_web(search_query, max_results=5) if results: print(f"\n🔍 搜索结果 for '{search_query}':\n") print(results) else: print("❌ 搜索失败或未找到结果") continue if not user_input: continue # 使用流式方法发送消息 response = self.send_message_stream(user_input) print() # 空行分隔 except KeyboardInterrupt: print("\n再见!") break except EOFError: print("\n再见!") break def show_help(self): """显示帮助信息""" print("\n可用命令:") print(" /multiline - 进入多行输入模式") print(" /clear - 清除对话历史") print(" /search <关键词> - 手动触发网络搜索") print(" /help - 显示帮助信息") print(" quit, exit - 退出程序") print("\n自动搜索触发条件:") print(" 当问题包含时间相关词汇(今天、最新、现在等)") print(" 或需要实时信息(天气、新闻、实时数据等)时") print(" 系统会自动联网搜索最新信息") def main(): # 配置API密钥 deepseek_api_key = "sk-f4e5e260d48f4d22b71dd991de75d31b" bocha_api_key = "sk-3cd80b05e77d42aebbe8579acf9bdd0f" # 你的博查API密钥 if not deepseek_api_key: print("请设置DeepSeek API密钥") deepseek_api_key = input("请输入您的DeepSeek API密钥: ").strip() chat = DeepSeekTerminalChat(deepseek_api_key, bocha_api_key) chat.start_chat() if __name__ == "__main__": main() 这个里面 /search 只是调用了搜索功能 没有结合我的问题和搜索结果 来给我做出回答 帮我完善这部分
08-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值