File size: 1,097 Bytes
fbf3c28 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | """
id: web_search
title: Web Search (DuckDuckGo)
author: admin
description: Search the web via DuckDuckGo HTML and return titles/links/snippets.
version: 0.1.0
license: Proprietary
"""
import re
import urllib.parse
import subprocess
class Tools:
def search(self, query: str, max_results: int = 5) -> dict:
q = urllib.parse.quote_plus(query)
cmd = f"curl -sSL 'https://duckduckgo.com/html/?q={q}'"
p = subprocess.run(
["bash", "-lc", cmd], capture_output=True, text=True, timeout=20
)
html = p.stdout
# very rough parse
results = []
for m in re.finditer(
r'<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)</a>', html
):
href = re.sub(r"^/l/\?kh=-1&uddg=", "", m.group(1))
title = re.sub("<[^<]+?>", "", m.group(2))
href = urllib.parse.unquote(href)
results.append({"title": title, "url": href})
if len(results) >= max_results:
break
return {"query": query, "results": results, "exit_code": p.returncode}
|