webscout 2025.10.11__py3-none-any.whl → 2025.10.14.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of webscout might be problematic. Click here for more details.

Files changed (47) hide show
  1. webscout/Provider/Andi.py +1 -1
  2. webscout/Provider/ChatGPTClone.py +2 -1
  3. webscout/__init__.py +1 -4
  4. webscout/auth/routes.py +2 -3
  5. webscout/cli.py +4 -2
  6. webscout/search/__init__.py +51 -0
  7. webscout/search/base.py +195 -0
  8. webscout/search/duckduckgo_main.py +54 -0
  9. webscout/search/engines/__init__.py +48 -0
  10. webscout/search/engines/bing.py +84 -0
  11. webscout/search/engines/bing_news.py +52 -0
  12. webscout/search/engines/brave.py +43 -0
  13. webscout/search/engines/duckduckgo/__init__.py +25 -0
  14. webscout/search/engines/duckduckgo/answers.py +78 -0
  15. webscout/search/engines/duckduckgo/base.py +187 -0
  16. webscout/search/engines/duckduckgo/images.py +97 -0
  17. webscout/search/engines/duckduckgo/maps.py +168 -0
  18. webscout/search/engines/duckduckgo/news.py +68 -0
  19. webscout/search/engines/duckduckgo/suggestions.py +21 -0
  20. webscout/search/engines/duckduckgo/text.py +211 -0
  21. webscout/search/engines/duckduckgo/translate.py +47 -0
  22. webscout/search/engines/duckduckgo/videos.py +63 -0
  23. webscout/search/engines/duckduckgo/weather.py +74 -0
  24. webscout/search/engines/mojeek.py +37 -0
  25. webscout/search/engines/wikipedia.py +56 -0
  26. webscout/search/engines/yahoo.py +65 -0
  27. webscout/search/engines/yahoo_news.py +64 -0
  28. webscout/search/engines/yandex.py +43 -0
  29. webscout/search/engines/yep/__init__.py +13 -0
  30. webscout/search/engines/yep/base.py +32 -0
  31. webscout/search/engines/yep/images.py +99 -0
  32. webscout/search/engines/yep/suggestions.py +35 -0
  33. webscout/search/engines/yep/text.py +114 -0
  34. webscout/search/http_client.py +156 -0
  35. webscout/search/results.py +137 -0
  36. webscout/search/yep_main.py +44 -0
  37. webscout/version.py +1 -1
  38. webscout/version.py.bak +2 -0
  39. {webscout-2025.10.11.dist-info → webscout-2025.10.14.1.dist-info}/METADATA +3 -4
  40. {webscout-2025.10.11.dist-info → webscout-2025.10.14.1.dist-info}/RECORD +44 -15
  41. webscout/webscout_search.py +0 -1183
  42. webscout/webscout_search_async.py +0 -649
  43. webscout/yep_search.py +0 -346
  44. {webscout-2025.10.11.dist-info → webscout-2025.10.14.1.dist-info}/WHEEL +0 -0
  45. {webscout-2025.10.11.dist-info → webscout-2025.10.14.1.dist-info}/entry_points.txt +0 -0
  46. {webscout-2025.10.11.dist-info → webscout-2025.10.14.1.dist-info}/licenses/LICENSE.md +0 -0
  47. {webscout-2025.10.11.dist-info → webscout-2025.10.14.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,78 @@
1
+ """DuckDuckGo answers search."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ....exceptions import WebscoutE
6
+ from .base import DuckDuckGoBase
7
+
8
+
9
+ class DuckDuckGoAnswers(DuckDuckGoBase):
10
+ """DuckDuckGo instant answers."""
11
+
12
+ def run(self, *args, **kwargs) -> list[dict[str, str]]:
13
+ """Get instant answers from DuckDuckGo.
14
+
15
+ Args:
16
+ keywords: Search query.
17
+
18
+ Returns:
19
+ List of answer dictionaries.
20
+ """
21
+ keywords = args[0] if args else kwargs.get("keywords")
22
+
23
+ assert keywords, "keywords is mandatory"
24
+
25
+ payload = {
26
+ "q": f"what is {keywords}",
27
+ "format": "json",
28
+ }
29
+ resp_content = self._get_url("GET", "https://api.duckduckgo.com/", params=payload).content
30
+ page_data = self.json_loads(resp_content)
31
+
32
+ results = []
33
+ answer = page_data.get("AbstractText")
34
+ url = page_data.get("AbstractURL")
35
+ if answer:
36
+ results.append(
37
+ {
38
+ "icon": None,
39
+ "text": answer,
40
+ "topic": None,
41
+ "url": url,
42
+ }
43
+ )
44
+
45
+ # related
46
+ payload = {
47
+ "q": f"{keywords}",
48
+ "format": "json",
49
+ }
50
+ resp_content = self._get_url("GET", "https://api.duckduckgo.com/", params=payload).content
51
+ resp_json = self.json_loads(resp_content)
52
+ page_data = resp_json.get("RelatedTopics", [])
53
+
54
+ for row in page_data:
55
+ topic = row.get("Name")
56
+ if not topic:
57
+ icon = row["Icon"].get("URL")
58
+ results.append(
59
+ {
60
+ "icon": f"https://duckduckgo.com{icon}" if icon else "",
61
+ "text": row["Text"],
62
+ "topic": None,
63
+ "url": row["FirstURL"],
64
+ }
65
+ )
66
+ else:
67
+ for subrow in row["Topics"]:
68
+ icon = subrow["Icon"].get("URL")
69
+ results.append(
70
+ {
71
+ "icon": f"https://duckduckgo.com{icon}" if icon else "",
72
+ "text": subrow["Text"],
73
+ "topic": topic,
74
+ "url": subrow["FirstURL"],
75
+ }
76
+ )
77
+
78
+ return results
@@ -0,0 +1,187 @@
1
+ """Base class for DuckDuckGo search implementations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ from functools import cached_property
8
+ from itertools import cycle, islice
9
+ from random import choice
10
+ from time import sleep, time
11
+ from typing import Any
12
+
13
+ try:
14
+ import trio
15
+ except ImportError:
16
+ pass
17
+
18
+ import curl_cffi.requests
19
+
20
+ try:
21
+ from lxml.html import HTMLParser as LHTMLParser
22
+ from lxml.html import document_fromstring
23
+ LXML_AVAILABLE = True
24
+ except ImportError:
25
+ LXML_AVAILABLE = False
26
+
27
+ from ....exceptions import RatelimitE, TimeoutE, WebscoutE
28
+ from ....utils import (
29
+ _extract_vqd,
30
+ _normalize,
31
+ _normalize_url,
32
+ json_loads,
33
+ )
34
+ from ....litagent import LitAgent
35
+
36
+
37
+ class DuckDuckGoBase:
38
+ """Base class for DuckDuckGo search operations."""
39
+
40
+ _executor: ThreadPoolExecutor = ThreadPoolExecutor()
41
+ _impersonates = (
42
+ "chrome99", "chrome100", "chrome101", "chrome104", "chrome107", "chrome110",
43
+ "chrome116", "chrome119", "chrome120", "chrome123", "chrome124", "chrome131", "chrome133a",
44
+ "chrome99_android", "chrome131_android",
45
+ "safari15_3", "safari15_5", "safari17_0", "safari17_2_ios", "safari18_0", "safari18_0_ios",
46
+ "edge99", "edge101",
47
+ "firefox133", "firefox135",
48
+ )
49
+
50
+ def __init__(
51
+ self,
52
+ headers: dict[str, str] | None = None,
53
+ proxy: str | None = None,
54
+ proxies: dict[str, str] | str | None = None,
55
+ timeout: int | None = 10,
56
+ verify: bool = True,
57
+ ) -> None:
58
+ """Initialize DuckDuckGo base client.
59
+
60
+ Args:
61
+ headers: Dictionary of headers for the HTTP client.
62
+ proxy: Proxy for the HTTP client (http/https/socks5).
63
+ proxies: Deprecated, use proxy instead.
64
+ timeout: Timeout value for the HTTP client.
65
+ verify: SSL verification when making requests.
66
+ """
67
+ ddgs_proxy: str | None = os.environ.get("DDGS_PROXY")
68
+ self.proxy: str | None = ddgs_proxy if ddgs_proxy else proxy
69
+
70
+ if not proxy and proxies:
71
+ self.proxy = proxies.get("http") or proxies.get("https") if isinstance(proxies, dict) else proxies
72
+
73
+ default_headers = {
74
+ **LitAgent().generate_fingerprint(),
75
+ "Origin": "https://duckduckgo.com",
76
+ "Referer": "https://duckduckgo.com/",
77
+ }
78
+
79
+ self.headers = headers if headers else {}
80
+ self.headers.update(default_headers)
81
+
82
+ impersonate_browser = choice(self._impersonates)
83
+ self.client = curl_cffi.requests.Session(
84
+ headers=self.headers,
85
+ proxies={'http': self.proxy, 'https': self.proxy} if self.proxy else None,
86
+ timeout=timeout,
87
+ impersonate=impersonate_browser,
88
+ verify=verify,
89
+ )
90
+ self.timeout = timeout
91
+ self.sleep_timestamp = 0.0
92
+
93
+ # Utility methods
94
+ self.cycle = cycle
95
+ self.islice = islice
96
+
97
+ @cached_property
98
+ def parser(self) -> Any:
99
+ """Get HTML parser."""
100
+ if not LXML_AVAILABLE:
101
+ raise ImportError("lxml is required for HTML parsing")
102
+
103
+ class Parser:
104
+ def __init__(self):
105
+ self.lhtml_parser = LHTMLParser(
106
+ remove_blank_text=True,
107
+ remove_comments=True,
108
+ remove_pis=True,
109
+ collect_ids=False
110
+ )
111
+ self.etree = __import__('lxml.etree', fromlist=['Element'])
112
+
113
+ def fromstring(self, html: bytes | str) -> Any:
114
+ return document_fromstring(html, parser=self.lhtml_parser)
115
+
116
+ return Parser()
117
+
118
+ def _sleep(self, sleeptime: float = 0.75) -> None:
119
+ """Sleep between API requests."""
120
+ delay = 0.0 if not self.sleep_timestamp else 0.0 if time() - self.sleep_timestamp >= 20 else sleeptime
121
+ self.sleep_timestamp = time()
122
+ sleep(delay)
123
+
124
+ def _get_url(
125
+ self,
126
+ method: str,
127
+ url: str,
128
+ params: dict[str, str] | None = None,
129
+ content: bytes | None = None,
130
+ data: dict[str, str] | None = None,
131
+ headers: dict[str, str] | None = None,
132
+ cookies: dict[str, str] | None = None,
133
+ json: Any = None,
134
+ timeout: float | None = None,
135
+ ) -> Any:
136
+ """Make HTTP request."""
137
+ self._sleep()
138
+ try:
139
+ request_kwargs = {
140
+ "params": params,
141
+ "headers": headers,
142
+ "json": json,
143
+ "timeout": timeout or self.timeout,
144
+ }
145
+
146
+ if isinstance(cookies, dict):
147
+ request_kwargs["cookies"] = cookies
148
+
149
+ if method == "GET":
150
+ if content:
151
+ request_kwargs["data"] = content
152
+ resp = self.client.get(url, **request_kwargs)
153
+ elif method == "POST":
154
+ if data or content:
155
+ request_kwargs["data"] = data or content
156
+ resp = self.client.post(url, **request_kwargs)
157
+ else:
158
+ if data or content:
159
+ request_kwargs["data"] = data or content
160
+ resp = self.client.request(method, url, **request_kwargs)
161
+ except Exception as ex:
162
+ if "time" in str(ex).lower():
163
+ raise TimeoutE(f"{url} {type(ex).__name__}: {ex}") from ex
164
+ raise WebscoutE(f"{url} {type(ex).__name__}: {ex}") from ex
165
+
166
+ if resp.status_code == 200:
167
+ return resp
168
+ elif resp.status_code in (202, 301, 403, 400, 429, 418):
169
+ raise RatelimitE(f"{resp.url} {resp.status_code} Ratelimit")
170
+ raise WebscoutE(f"{resp.url} return None. {params=} {content=} {data=}")
171
+
172
+ def _get_vqd(self, keywords: str) -> str:
173
+ """Get vqd value for a search query."""
174
+ resp_content = self._get_url("GET", "https://duckduckgo.com", params={"q": keywords}).content
175
+ return _extract_vqd(resp_content, keywords)
176
+
177
+ def json_loads(self, obj: str | bytes) -> Any:
178
+ """Load JSON from string or bytes."""
179
+ return json_loads(obj)
180
+
181
+ def _normalize(self, text: str) -> str:
182
+ """Normalize text."""
183
+ return _normalize(text)
184
+
185
+ def _normalize_url(self, url: str) -> str:
186
+ """Normalize URL."""
187
+ return _normalize_url(url)
@@ -0,0 +1,97 @@
1
+ """DuckDuckGo image search."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ....exceptions import WebscoutE
6
+ from .base import DuckDuckGoBase
7
+
8
+
9
+ class DuckDuckGoImages(DuckDuckGoBase):
10
+ """DuckDuckGo image search."""
11
+
12
+ def run(self, *args, **kwargs) -> list[dict[str, str]]:
13
+ """Perform image search on DuckDuckGo.
14
+
15
+ Args:
16
+ keywords: Search query.
17
+ region: Region code.
18
+ safesearch: on, moderate, or off.
19
+ timelimit: d, w, m, or y.
20
+ size: Small, Medium, Large, Wallpaper.
21
+ color: color name or Monochrome.
22
+ type_image: photo, clipart, gif, transparent, line.
23
+ layout: Square, Tall, Wide.
24
+ license_image: any, Public, Share, etc.
25
+ max_results: Maximum number of results.
26
+
27
+ Returns:
28
+ List of image result dictionaries.
29
+ """
30
+ keywords = args[0] if args else kwargs.get("keywords")
31
+ region = args[1] if len(args) > 1 else kwargs.get("region", "wt-wt")
32
+ safesearch = args[2] if len(args) > 2 else kwargs.get("safesearch", "moderate")
33
+ timelimit = args[3] if len(args) > 3 else kwargs.get("timelimit")
34
+ size = args[4] if len(args) > 4 else kwargs.get("size")
35
+ color = args[5] if len(args) > 5 else kwargs.get("color")
36
+ type_image = args[6] if len(args) > 6 else kwargs.get("type_image")
37
+ layout = args[7] if len(args) > 7 else kwargs.get("layout")
38
+ license_image = args[8] if len(args) > 8 else kwargs.get("license_image")
39
+ max_results = args[9] if len(args) > 9 else kwargs.get("max_results")
40
+
41
+ assert keywords, "keywords is mandatory"
42
+
43
+ vqd = self._get_vqd(keywords)
44
+
45
+ safesearch_base = {"on": "1", "moderate": "1", "off": "-1"}
46
+ timelimit = f"time:{timelimit}" if timelimit else ""
47
+ size = f"size:{size}" if size else ""
48
+ color = f"color:{color}" if color else ""
49
+ type_image = f"type:{type_image}" if type_image else ""
50
+ layout = f"layout:{layout}" if layout else ""
51
+ license_image = f"license:{license_image}" if license_image else ""
52
+ payload = {
53
+ "l": region,
54
+ "o": "json",
55
+ "q": keywords,
56
+ "vqd": vqd,
57
+ "f": f"{timelimit},{size},{color},{type_image},{layout},{license_image}",
58
+ "p": safesearch_base[safesearch.lower()],
59
+ }
60
+
61
+ cache = set()
62
+ results: list[dict[str, str]] = []
63
+
64
+ def _images_page(s: int) -> list[dict[str, str]]:
65
+ payload["s"] = f"{s}"
66
+ resp_content = self._get_url("GET", "https://duckduckgo.com/i.js", params=payload).content
67
+ resp_json = self.json_loads(resp_content)
68
+
69
+ page_data = resp_json.get("results", [])
70
+ page_results = []
71
+ for row in page_data:
72
+ image_url = row.get("image")
73
+ if image_url and image_url not in cache:
74
+ cache.add(image_url)
75
+ result = {
76
+ "title": row["title"],
77
+ "image": self._normalize_url(image_url),
78
+ "thumbnail": self._normalize_url(row["thumbnail"]),
79
+ "url": self._normalize_url(row["url"]),
80
+ "height": row["height"],
81
+ "width": row["width"],
82
+ "source": row["source"],
83
+ }
84
+ page_results.append(result)
85
+ return page_results
86
+
87
+ slist = [0]
88
+ if max_results:
89
+ max_results = min(max_results, 500)
90
+ slist.extend(range(100, max_results, 100))
91
+ try:
92
+ for r in self._executor.map(_images_page, slist):
93
+ results.extend(r)
94
+ except Exception as e:
95
+ raise e
96
+
97
+ return list(self.islice(results, max_results))
@@ -0,0 +1,168 @@
1
+ from __future__ import annotations
2
+
3
+ from decimal import Decimal
4
+
5
+ from ....exceptions import WebscoutE
6
+ from .base import DuckDuckGoBase
7
+
8
+
9
+ class DuckDuckGoMaps(DuckDuckGoBase):
10
+ def run(self, *args, **kwargs) -> list[dict[str, str]]:
11
+ keywords = args[0] if args else kwargs.get("keywords")
12
+ place = args[1] if len(args) > 1 else kwargs.get("place")
13
+ street = args[2] if len(args) > 2 else kwargs.get("street")
14
+ city = args[3] if len(args) > 3 else kwargs.get("city")
15
+ county = args[4] if len(args) > 4 else kwargs.get("county")
16
+ state = args[5] if len(args) > 5 else kwargs.get("state")
17
+ country = args[6] if len(args) > 6 else kwargs.get("country")
18
+ postalcode = args[7] if len(args) > 7 else kwargs.get("postalcode")
19
+ latitude = args[8] if len(args) > 8 else kwargs.get("latitude")
20
+ longitude = args[9] if len(args) > 9 else kwargs.get("longitude")
21
+ radius = args[10] if len(args) > 10 else kwargs.get("radius", 0)
22
+ max_results = args[11] if len(args) > 11 else kwargs.get("max_results")
23
+
24
+ assert keywords, "keywords is mandatory"
25
+
26
+ vqd = self._get_vqd(keywords)
27
+
28
+ # if longitude and latitude are specified, skip the request about bbox to the nominatim api
29
+ if latitude and longitude:
30
+ lat_t = Decimal(latitude.replace(",", "."))
31
+ lat_b = Decimal(latitude.replace(",", "."))
32
+ lon_l = Decimal(longitude.replace(",", "."))
33
+ lon_r = Decimal(longitude.replace(",", "."))
34
+ if radius == 0:
35
+ radius = 1
36
+ # otherwise request about bbox to nominatim api
37
+ else:
38
+ if place:
39
+ params = {
40
+ "q": place,
41
+ "polygon_geojson": "0",
42
+ "format": "jsonv2",
43
+ }
44
+ else:
45
+ params = {
46
+ "polygon_geojson": "0",
47
+ "format": "jsonv2",
48
+ }
49
+ if street:
50
+ params["street"] = street
51
+ if city:
52
+ params["city"] = city
53
+ if county:
54
+ params["county"] = county
55
+ if state:
56
+ params["state"] = state
57
+ if country:
58
+ params["country"] = country
59
+ if postalcode:
60
+ params["postalcode"] = postalcode
61
+ # request nominatim api to get coordinates box
62
+ resp_content = self._get_url(
63
+ "GET",
64
+ "https://nominatim.openstreetmap.org/search.php",
65
+ params=params,
66
+ ).content
67
+ if resp_content == b"[]":
68
+ raise WebscoutE("maps() Coordinates are not found, check function parameters.")
69
+ resp_json = self.json_loads(resp_content)
70
+ coordinates = resp_json[0]["boundingbox"]
71
+ lat_t, lon_l = Decimal(coordinates[1]), Decimal(coordinates[2])
72
+ lat_b, lon_r = Decimal(coordinates[0]), Decimal(coordinates[3])
73
+
74
+ # if a radius is specified, expand the search square
75
+ lat_t += Decimal(radius) * Decimal(0.008983)
76
+ lat_b -= Decimal(radius) * Decimal(0.008983)
77
+ lon_l -= Decimal(radius) * Decimal(0.008983)
78
+ lon_r += Decimal(radius) * Decimal(0.008983)
79
+
80
+ cache = set()
81
+ results: list[dict[str, str]] = []
82
+
83
+ def _maps_page(
84
+ bbox: tuple[Decimal, Decimal, Decimal, Decimal],
85
+ ) -> list[dict[str, str]] | None:
86
+ if max_results and len(results) >= max_results:
87
+ return None
88
+ lat_t, lon_l, lat_b, lon_r = bbox
89
+ params = {
90
+ "q": keywords,
91
+ "vqd": vqd,
92
+ "tg": "maps_places",
93
+ "rt": "D",
94
+ "mkexp": "b",
95
+ "wiki_info": "1",
96
+ "is_requery": "1",
97
+ "bbox_tl": f"{lat_t},{lon_l}",
98
+ "bbox_br": f"{lat_b},{lon_r}",
99
+ "strict_bbox": "1",
100
+ }
101
+ resp_content = self._get_url("GET", "https://duckduckgo.com/local.js", params=params).content
102
+ resp_json = self.json_loads(resp_content)
103
+ page_data = resp_json.get("results", [])
104
+
105
+ page_results = []
106
+ for res in page_data:
107
+ r_name = f'{res["name"]} {res["address"]}'
108
+ if r_name in cache:
109
+ continue
110
+ else:
111
+ cache.add(r_name)
112
+ result = {
113
+ "title": res["name"],
114
+ "address": res["address"],
115
+ "country_code": res["country_code"],
116
+ "url": self._normalize_url(res["website"]),
117
+ "phone": res["phone"] or "",
118
+ "latitude": res["coordinates"]["latitude"],
119
+ "longitude": res["coordinates"]["longitude"],
120
+ "source": self._normalize_url(res["url"]),
121
+ "image": x.get("image", "") if (x := res["embed"]) else "",
122
+ "desc": x.get("description", "") if (x := res["embed"]) else "",
123
+ "hours": res["hours"] or "",
124
+ "category": res["ddg_category"] or "",
125
+ "facebook": f"www.facebook.com/profile.php?id={x}" if (x := res["facebook_id"]) else "",
126
+ "instagram": f"https://www.instagram.com/{x}" if (x := res["instagram_id"]) else "",
127
+ "twitter": f"https://twitter.com/{x}" if (x := res["twitter_id"]) else "",
128
+ }
129
+ page_results.append(result)
130
+ return page_results
131
+
132
+ start_bbox = (lat_t, lon_l, lat_b, lon_r)
133
+ work_bboxes = [start_bbox]
134
+ while work_bboxes:
135
+ queue_bboxes = []
136
+ tasks = []
137
+ for bbox in work_bboxes:
138
+ tasks.append(bbox)
139
+ if self._calculate_distance(lat_t, lon_l, lat_b, lon_r) > 1:
140
+ lat_t, lon_l, lat_b, lon_r = bbox
141
+ lat_middle = (lat_t + lat_b) / 2
142
+ lon_middle = (lon_l + lon_r) / 2
143
+ bbox1 = (lat_t, lon_l, lat_middle, lon_middle)
144
+ bbox2 = (lat_t, lon_middle, lat_middle, lon_r)
145
+ bbox3 = (lat_middle, lon_l, lat_b, lon_middle)
146
+ bbox4 = (lat_middle, lon_middle, lat_b, lon_r)
147
+ queue_bboxes.extend([bbox1, bbox2, bbox3, bbox4])
148
+
149
+ work_bboxes_results = []
150
+ try:
151
+ for r in self._executor.map(_maps_page, tasks):
152
+ if r:
153
+ work_bboxes_results.extend(r)
154
+ except Exception as e:
155
+ raise e
156
+
157
+ for x in work_bboxes_results:
158
+ if isinstance(x, list):
159
+ results.extend(x)
160
+ elif isinstance(x, dict):
161
+ results.append(x)
162
+
163
+ work_bboxes = queue_bboxes
164
+ if not max_results or len(results) >= max_results or len(work_bboxes_results) == 0:
165
+ break
166
+
167
+ return list(self.islice(results, max_results))
168
+
@@ -0,0 +1,68 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime, timezone
4
+
5
+ from ....exceptions import WebscoutE
6
+ from .base import DuckDuckGoBase
7
+
8
+
9
+ class DuckDuckGoNews(DuckDuckGoBase):
10
+ def run(self, *args, **kwargs) -> list[dict[str, str]]:
11
+ keywords = args[0] if args else kwargs.get("keywords")
12
+ region = args[1] if len(args) > 1 else kwargs.get("region", "wt-wt")
13
+ safesearch = args[2] if len(args) > 2 else kwargs.get("safesearch", "moderate")
14
+ timelimit = args[3] if len(args) > 3 else kwargs.get("timelimit")
15
+ max_results = args[4] if len(args) > 4 else kwargs.get("max_results")
16
+
17
+ assert keywords, "keywords is mandatory"
18
+
19
+ vqd = self._get_vqd(keywords)
20
+
21
+ safesearch_base = {"on": "1", "moderate": "-1", "off": "-2"}
22
+ payload = {
23
+ "l": region,
24
+ "o": "json",
25
+ "noamp": "1",
26
+ "q": keywords,
27
+ "vqd": vqd,
28
+ "p": safesearch_base[safesearch.lower()],
29
+ }
30
+ if timelimit:
31
+ payload["df"] = timelimit
32
+
33
+ cache = set()
34
+ results: list[dict[str, str]] = []
35
+
36
+ def _news_page(s: int) -> list[dict[str, str]]:
37
+ payload["s"] = f"{s}"
38
+ resp_content = self._get_url("GET", "https://duckduckgo.com/news.js", params=payload).content
39
+ resp_json = self.json_loads(resp_content)
40
+ page_data = resp_json.get("results", [])
41
+ page_results = []
42
+ for row in page_data:
43
+ if row["url"] not in cache:
44
+ cache.add(row["url"])
45
+ image_url = row.get("image", None)
46
+ result = {
47
+ "date": datetime.fromtimestamp(row["date"], timezone.utc).isoformat(),
48
+ "title": row["title"],
49
+ "body": self._normalize(row["excerpt"]),
50
+ "url": self._normalize_url(row["url"]),
51
+ "image": self._normalize_url(image_url),
52
+ "source": row["source"],
53
+ }
54
+ page_results.append(result)
55
+ return page_results
56
+
57
+ slist = [0]
58
+ if max_results:
59
+ max_results = min(max_results, 120)
60
+ slist.extend(range(30, max_results, 30))
61
+ try:
62
+ for r in self._executor.map(_news_page, slist):
63
+ results.extend(r)
64
+ except Exception as e:
65
+ raise e
66
+
67
+ return list(self.islice(results, max_results))
68
+
@@ -0,0 +1,21 @@
1
+ from __future__ import annotations
2
+
3
+ from ....exceptions import WebscoutE
4
+ from .base import DuckDuckGoBase
5
+
6
+
7
+ class DuckDuckGoSuggestions(DuckDuckGoBase):
8
+ def run(self, *args, **kwargs) -> list[dict[str, str]]:
9
+ keywords = args[0] if args else kwargs.get("keywords")
10
+ region = args[1] if len(args) > 1 else kwargs.get("region", "wt-wt")
11
+
12
+ assert keywords, "keywords is mandatory"
13
+
14
+ payload = {
15
+ "q": keywords,
16
+ "kl": region,
17
+ }
18
+ resp_content = self._get_url("GET", "https://duckduckgo.com/ac/", params=payload).content
19
+ page_data = self.json_loads(resp_content)
20
+ return [r for r in page_data]
21
+