# tools/news_tool.py import requests from bs4 import BeautifulSoup def search_latest_news(query: str) -> str: """ 使用requests和BeautifulSoup抓取DuckDuckGo搜索结果来模拟新闻搜索。 """ print(f"--- 正在执行工具: search_latest_news, 参数: {query} ---") headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" } url = f"https://html.duckduckgo.com/html/?q={query}" try: response = requests.get(url, headers=headers, timeout=5) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") results = soup.find_all("div", class_="result") if not results: return "没有找到相关的新闻报道。" # 提取前三个结果的摘要 snippets = [] for result in results[:3]: title_tag = result.find("a", class_="result__a") snippet_tag = result.find("a", class_="result__snippet") if title_tag and snippet_tag: title = title_tag.text.strip() snippet = snippet_tag.text.strip() snippets.append(f"标题: {title}\n摘要: {snippet}\n") return "\n---\n".join(snippets) except requests.RequestException as e: return f"搜索新闻时发生网络错误: {e}" except Exception as e: return f"解析新闻搜索结果时发生错误: {e}"