Spaces:
Sleeping
Sleeping
| # tools/news_tool.py | |
| import requests | |
| from bs4 import BeautifulSoup | |
| def search_latest_news(query: str) -> str: | |
| """ | |
| Simulates a news search by scraping DuckDuckGo search results using requests and BeautifulSoup. | |
| """ | |
| print(f"--- Executing Tool: search_latest_news, Parameters: {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 "No relevant news articles were found." | |
| # Extract snippets from the top 3 results | |
| 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: {title}\nSnippet: {snippet}\n") | |
| return "\n---\n".join(snippets) | |
| except requests.RequestException as e: | |
| return f"A network error occurred while searching for news: {e}" | |
| except Exception as e: | |
| return f"An error occurred while parsing news search results: {e}" | |