Update web_search.py
Browse files- web_search.py +17 -14
web_search.py
CHANGED
|
@@ -1,17 +1,20 @@
|
|
| 1 |
-
# web_search.py
|
| 2 |
import requests
|
| 3 |
|
| 4 |
def web_search(query, max_results=3):
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# web_search.py
|
| 2 |
import requests
|
| 3 |
|
| 4 |
def web_search(query, max_results=3):
|
| 5 |
+
try:
|
| 6 |
+
url = f"https://duckduckgo.com/html/?q={query}"
|
| 7 |
+
headers = {'User-Agent': 'Mozilla/5.0'}
|
| 8 |
+
response = requests.get(url, headers=headers)
|
| 9 |
+
results = []
|
| 10 |
+
for line in response.text.split("\n"):
|
| 11 |
+
if "<a rel=\"nofollow\"" in line and 'href="' in line:
|
| 12 |
+
start = line.find('href="') + 6
|
| 13 |
+
end = line.find('"', start)
|
| 14 |
+
link = line[start:end]
|
| 15 |
+
results.append(link)
|
| 16 |
+
if len(results) >= max_results:
|
| 17 |
+
break
|
| 18 |
+
return "\n".join(results)
|
| 19 |
+
except Exception as e:
|
| 20 |
+
return f"[Web search failed: {e}]"
|