webscout 6.9__py3-none-any.whl → 7.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.
- webscout/AIbase.py +12 -2
- webscout/DWEBS.py +38 -22
- webscout/Extra/autocoder/autocoder_utiles.py +68 -7
- webscout/Extra/autollama.py +0 -16
- webscout/Extra/gguf.py +0 -13
- webscout/LLM.py +1 -1
- webscout/Provider/AISEARCH/DeepFind.py +251 -0
- webscout/Provider/AISEARCH/__init__.py +2 -2
- webscout/Provider/AISEARCH/felo_search.py +167 -118
- webscout/Provider/Blackboxai.py +136 -137
- webscout/Provider/Cloudflare.py +92 -78
- webscout/Provider/Deepinfra.py +59 -35
- webscout/Provider/Glider.py +222 -0
- webscout/Provider/Groq.py +26 -18
- webscout/Provider/HF_space/__init__.py +0 -0
- webscout/Provider/HF_space/qwen_qwen2.py +206 -0
- webscout/Provider/Jadve.py +108 -77
- webscout/Provider/Llama3.py +117 -94
- webscout/Provider/Marcus.py +65 -10
- webscout/Provider/Netwrck.py +61 -49
- webscout/Provider/PI.py +77 -122
- webscout/Provider/PizzaGPT.py +129 -82
- webscout/Provider/TextPollinationsAI.py +229 -0
- webscout/Provider/Youchat.py +28 -22
- webscout/Provider/__init__.py +12 -4
- webscout/Provider/askmyai.py +2 -2
- webscout/Provider/chatglm.py +205 -0
- webscout/Provider/dgaf.py +215 -0
- webscout/Provider/gaurish.py +106 -66
- webscout/Provider/hermes.py +219 -0
- webscout/Provider/llamatutor.py +72 -62
- webscout/Provider/llmchat.py +62 -35
- webscout/Provider/meta.py +6 -6
- webscout/Provider/multichat.py +205 -104
- webscout/Provider/typegpt.py +26 -23
- webscout/Provider/yep.py +3 -3
- webscout/litagent/__init__.py +3 -146
- webscout/litagent/agent.py +120 -0
- webscout/litagent/constants.py +31 -0
- webscout/tempid.py +0 -4
- webscout/version.py +1 -1
- webscout/webscout_search.py +1141 -1140
- webscout/webscout_search_async.py +635 -635
- {webscout-6.9.dist-info → webscout-7.1.dist-info}/METADATA +37 -33
- {webscout-6.9.dist-info → webscout-7.1.dist-info}/RECORD +49 -41
- {webscout-6.9.dist-info → webscout-7.1.dist-info}/WHEEL +1 -1
- webscout/Provider/AISEARCH/ooai.py +0 -155
- webscout/Provider/RUBIKSAI.py +0 -272
- {webscout-6.9.dist-info → webscout-7.1.dist-info}/LICENSE.md +0 -0
- {webscout-6.9.dist-info → webscout-7.1.dist-info}/entry_points.txt +0 -0
- {webscout-6.9.dist-info → webscout-7.1.dist-info}/top_level.txt +0 -0
|
@@ -1,636 +1,636 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import asyncio
|
|
4
|
-
import logging
|
|
5
|
-
import os
|
|
6
|
-
import warnings
|
|
7
|
-
from datetime import datetime, timezone
|
|
8
|
-
from functools import cached_property
|
|
9
|
-
from itertools import cycle
|
|
10
|
-
from random import choice, shuffle
|
|
11
|
-
from time import time
|
|
12
|
-
from types import TracebackType
|
|
13
|
-
from typing import Any, Dict, List, Optional, Type, Union, cast
|
|
14
|
-
|
|
15
|
-
import httpx
|
|
16
|
-
from lxml.etree import _Element
|
|
17
|
-
from lxml.html import HTMLParser as LHTMLParser
|
|
18
|
-
from lxml.html import document_fromstring
|
|
19
|
-
|
|
20
|
-
from .exceptions import RatelimitE, TimeoutE, WebscoutE
|
|
21
|
-
from .utils import (
|
|
22
|
-
_expand_proxy_tb_alias,
|
|
23
|
-
_extract_vqd,
|
|
24
|
-
_normalize,
|
|
25
|
-
_normalize_url,
|
|
26
|
-
json_loads,
|
|
27
|
-
)
|
|
28
|
-
|
|
29
|
-
logger = logging.getLogger("webscout.AsyncWEBS")
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
class AsyncWEBS:
|
|
33
|
-
"""Asynchronous webscout class to get search results."""
|
|
34
|
-
|
|
35
|
-
_impersonates = (
|
|
36
|
-
"chrome_100", "chrome_101", "chrome_104", "chrome_105", "chrome_106", "chrome_107",
|
|
37
|
-
"chrome_108", "chrome_109", "chrome_114", "chrome_116", "chrome_117", "chrome_118",
|
|
38
|
-
"chrome_119", "chrome_120", "chrome_123", "chrome_124", "chrome_126", "chrome_127",
|
|
39
|
-
"chrome_128", "chrome_129", "chrome_130", "chrome_131",
|
|
40
|
-
"safari_ios_16.5", "safari_ios_17.2", "safari_ios_17.4.1", "safari_ios_18.1.1",
|
|
41
|
-
"safari_15.3", "safari_15.5", "safari_15.6.1", "safari_16", "safari_16.5",
|
|
42
|
-
"safari_17.0", "safari_17.2.1", "safari_17.4.1", "safari_17.5",
|
|
43
|
-
"safari_18", "safari_18.2",
|
|
44
|
-
"safari_ipad_18",
|
|
45
|
-
"edge_101", "edge_122", "edge_127", "edge_131",
|
|
46
|
-
"firefox_109", "firefox_117", "firefox_128", "firefox_133",
|
|
47
|
-
)
|
|
48
|
-
|
|
49
|
-
def __init__(
|
|
50
|
-
self,
|
|
51
|
-
headers: Optional[Dict[str, str]] = None,
|
|
52
|
-
proxy: Optional[str] = None,
|
|
53
|
-
proxies: Union[Dict[str, str], str, None] = None, # deprecated
|
|
54
|
-
timeout: Optional[int] = 10,
|
|
55
|
-
) -> None:
|
|
56
|
-
"""Initialize the AsyncWEBS object.
|
|
57
|
-
|
|
58
|
-
Args:
|
|
59
|
-
headers (dict, optional): Dictionary of headers for the HTTP client. Defaults to None.
|
|
60
|
-
proxy (str, optional): proxy for the HTTP client, supports http/https/socks5 protocols.
|
|
61
|
-
example: "http://user:pass@example.com:3128". Defaults to None.
|
|
62
|
-
timeout (int, optional): Timeout value for the HTTP client. Defaults to 10.
|
|
63
|
-
"""
|
|
64
|
-
self.proxy: Optional[str] = _expand_proxy_tb_alias(proxy)
|
|
65
|
-
assert self.proxy is None or isinstance(self.proxy, str), "proxy must be a str"
|
|
66
|
-
if not proxy and proxies:
|
|
67
|
-
warnings.warn("'proxies' is deprecated, use 'proxy' instead.", stacklevel=1)
|
|
68
|
-
self.proxy = proxies.get("http") or proxies.get("https") if isinstance(proxies, dict) else proxies
|
|
69
|
-
|
|
70
|
-
default_headers = {
|
|
71
|
-
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
|
72
|
-
"Accept-Language": "en-US,en;q=0.5",
|
|
73
|
-
"Accept-Encoding": "gzip, deflate, br",
|
|
74
|
-
"DNT": "1",
|
|
75
|
-
"Connection": "keep-alive",
|
|
76
|
-
"Upgrade-Insecure-Requests": "1",
|
|
77
|
-
"Sec-Fetch-Dest": "document",
|
|
78
|
-
"Sec-Fetch-Mode": "navigate",
|
|
79
|
-
"Sec-Fetch-Site": "none",
|
|
80
|
-
"Sec-Fetch-User": "?1",
|
|
81
|
-
"Referer": "https://duckduckgo.com/",
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
self.headers = headers if headers else {}
|
|
85
|
-
self.headers.update(default_headers)
|
|
86
|
-
|
|
87
|
-
self.client = httpx.AsyncClient(
|
|
88
|
-
headers=self.headers,
|
|
89
|
-
proxies=self.proxy,
|
|
90
|
-
timeout=timeout,
|
|
91
|
-
follow_redirects=True,
|
|
92
|
-
verify=False,
|
|
93
|
-
)
|
|
94
|
-
self.sleep_timestamp = 0.0
|
|
95
|
-
|
|
96
|
-
async def __aenter__(self) -> AsyncWEBS:
|
|
97
|
-
return self
|
|
98
|
-
|
|
99
|
-
async def __aexit__(
|
|
100
|
-
self,
|
|
101
|
-
exc_type: Optional[Type[BaseException]] = None,
|
|
102
|
-
exc_val: Optional[BaseException] = None,
|
|
103
|
-
exc_tb: Optional[TracebackType] = None,
|
|
104
|
-
) -> None:
|
|
105
|
-
await self.client.aclose()
|
|
106
|
-
|
|
107
|
-
@cached_property
|
|
108
|
-
def parser(self) -> LHTMLParser:
|
|
109
|
-
"""Get HTML parser."""
|
|
110
|
-
return LHTMLParser(remove_blank_text=True, remove_comments=True, remove_pis=True, collect_ids=False)
|
|
111
|
-
|
|
112
|
-
async def _sleep(self, sleeptime: float = 2.0) -> None:
|
|
113
|
-
"""Sleep between API requests."""
|
|
114
|
-
delay = sleeptime if not self.sleep_timestamp else sleeptime if time() - self.sleep_timestamp >= 30 else sleeptime * 2
|
|
115
|
-
self.sleep_timestamp = time()
|
|
116
|
-
await asyncio.sleep(delay)
|
|
117
|
-
|
|
118
|
-
async def _get_url(
|
|
119
|
-
self,
|
|
120
|
-
method: str,
|
|
121
|
-
url: str,
|
|
122
|
-
params: Optional[Dict[str, str]] = None,
|
|
123
|
-
content: Optional[bytes] = None,
|
|
124
|
-
data: Optional[Dict[str, str]] = None,
|
|
125
|
-
) -> bytes:
|
|
126
|
-
"""Make HTTP request with proper rate limiting."""
|
|
127
|
-
await self._sleep()
|
|
128
|
-
try:
|
|
129
|
-
resp = await self.client.request(method, url, params=params, content=content, data=data)
|
|
130
|
-
|
|
131
|
-
# Add additional delay if we get a 429 or similar status
|
|
132
|
-
if resp.status_code in (429, 403, 503):
|
|
133
|
-
await asyncio.sleep(5.0) # Additional delay for rate limit responses
|
|
134
|
-
resp = await self.client.request(method, url, params=params, content=content, data=data)
|
|
135
|
-
|
|
136
|
-
except Exception as ex:
|
|
137
|
-
if "time" in str(ex).lower():
|
|
138
|
-
raise TimeoutE(f"{url} {type(ex).__name__}: {ex}") from ex
|
|
139
|
-
raise WebscoutE(f"{url} {type(ex).__name__}: {ex}") from ex
|
|
140
|
-
|
|
141
|
-
if resp.status_code == 200:
|
|
142
|
-
return resp.content
|
|
143
|
-
elif resp.status_code in (202, 301, 403, 429, 503):
|
|
144
|
-
raise RatelimitE(f"{url} {resp.status_code} Ratelimit - Please wait a few minutes before retrying")
|
|
145
|
-
raise WebscoutE(f"{url} return None. {params=} {content=} {data=}")
|
|
146
|
-
|
|
147
|
-
async def achat(self, keywords: str, model: str = "gpt-
|
|
148
|
-
"""Initiates async chat session with webscout AI.
|
|
149
|
-
|
|
150
|
-
Args:
|
|
151
|
-
keywords (str): The initial message or question to send to the AI.
|
|
152
|
-
model (str): The model to use: "gpt-
|
|
153
|
-
Defaults to "gpt-
|
|
154
|
-
|
|
155
|
-
Returns:
|
|
156
|
-
str: The response from the AI.
|
|
157
|
-
"""
|
|
158
|
-
result = await self._loop.run_in_executor(self._executor, super().chat, keywords, model)
|
|
159
|
-
return result
|
|
160
|
-
|
|
161
|
-
async def atext(
|
|
162
|
-
self,
|
|
163
|
-
keywords: str,
|
|
164
|
-
region: str = "wt-wt",
|
|
165
|
-
safesearch: str = "moderate",
|
|
166
|
-
timelimit: Optional[str] = None,
|
|
167
|
-
backend: str = "auto",
|
|
168
|
-
max_results: Optional[int] = None,
|
|
169
|
-
) -> List[Dict[str, str]]:
|
|
170
|
-
"""webscout async text search. Query params: https://duckduckgo.com/params.
|
|
171
|
-
|
|
172
|
-
Args:
|
|
173
|
-
keywords: keywords for query.
|
|
174
|
-
region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
|
|
175
|
-
safesearch: on, moderate, off. Defaults to "moderate".
|
|
176
|
-
timelimit: d, w, m, y. Defaults to None.
|
|
177
|
-
backend: auto, html, lite. Defaults to auto.
|
|
178
|
-
auto - try all backends in random order,
|
|
179
|
-
html - collect data from https://html.duckduckgo.com,
|
|
180
|
-
lite - collect data from https://lite.duckduckgo.com.
|
|
181
|
-
max_results: max number of results. If None, returns results only from the first response. Defaults to None.
|
|
182
|
-
|
|
183
|
-
Returns:
|
|
184
|
-
List of dictionaries with search results.
|
|
185
|
-
|
|
186
|
-
Raises:
|
|
187
|
-
WebscoutE: Base exception for webscout errors.
|
|
188
|
-
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
189
|
-
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
190
|
-
"""
|
|
191
|
-
if backend in ("api", "ecosia"):
|
|
192
|
-
warnings.warn(f"{backend=} is deprecated, using backend='auto'", stacklevel=2)
|
|
193
|
-
backend = "auto"
|
|
194
|
-
backends = ["html", "lite"] if backend == "auto" else [backend]
|
|
195
|
-
shuffle(backends)
|
|
196
|
-
|
|
197
|
-
results, err = [], None
|
|
198
|
-
for b in backends:
|
|
199
|
-
try:
|
|
200
|
-
if b == "html":
|
|
201
|
-
results = await self._text_html(keywords, region, timelimit, max_results)
|
|
202
|
-
elif b == "lite":
|
|
203
|
-
results = await self._text_lite(keywords, region, timelimit, max_results)
|
|
204
|
-
return results
|
|
205
|
-
except Exception as ex:
|
|
206
|
-
err = ex
|
|
207
|
-
|
|
208
|
-
raise WebscoutE(err)
|
|
209
|
-
|
|
210
|
-
async def _text_html(
|
|
211
|
-
self,
|
|
212
|
-
keywords: str,
|
|
213
|
-
region: str = "wt-wt",
|
|
214
|
-
timelimit: Optional[str] = None,
|
|
215
|
-
max_results: Optional[int] = None,
|
|
216
|
-
) -> List[Dict[str, str]]:
|
|
217
|
-
"""HTML backend for text search."""
|
|
218
|
-
assert keywords, "keywords is mandatory"
|
|
219
|
-
|
|
220
|
-
payload = {
|
|
221
|
-
"q": keywords,
|
|
222
|
-
"s": "0",
|
|
223
|
-
"o": "json",
|
|
224
|
-
"api": "d.js",
|
|
225
|
-
"vqd": "",
|
|
226
|
-
"kl": region,
|
|
227
|
-
"bing_market": region,
|
|
228
|
-
}
|
|
229
|
-
if timelimit:
|
|
230
|
-
payload["df"] = timelimit
|
|
231
|
-
|
|
232
|
-
cache = set()
|
|
233
|
-
results: List[Dict[str, str]] = []
|
|
234
|
-
|
|
235
|
-
for _ in range(5):
|
|
236
|
-
resp_content = await self._get_url("POST", "https://html.duckduckgo.com/html", data=payload)
|
|
237
|
-
if b"No results." in resp_content:
|
|
238
|
-
return results
|
|
239
|
-
|
|
240
|
-
tree = document_fromstring(resp_content, self.parser)
|
|
241
|
-
elements = tree.xpath("//div[h2]")
|
|
242
|
-
if not isinstance(elements, list):
|
|
243
|
-
return results
|
|
244
|
-
|
|
245
|
-
for e in elements:
|
|
246
|
-
if isinstance(e, _Element):
|
|
247
|
-
hrefxpath = e.xpath("./a/@href")
|
|
248
|
-
href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
|
|
249
|
-
if (
|
|
250
|
-
href
|
|
251
|
-
and href not in cache
|
|
252
|
-
and not href.startswith(
|
|
253
|
-
("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
|
|
254
|
-
)
|
|
255
|
-
):
|
|
256
|
-
cache.add(href)
|
|
257
|
-
titlexpath = e.xpath("./h2/a/text()")
|
|
258
|
-
title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
|
|
259
|
-
bodyxpath = e.xpath("./a//text()")
|
|
260
|
-
body = "".join(str(x) for x in bodyxpath) if bodyxpath and isinstance(bodyxpath, list) else ""
|
|
261
|
-
results.append(
|
|
262
|
-
{
|
|
263
|
-
"title": _normalize(title),
|
|
264
|
-
"href": _normalize_url(href),
|
|
265
|
-
"body": _normalize(body),
|
|
266
|
-
}
|
|
267
|
-
)
|
|
268
|
-
if max_results and len(results) >= max_results:
|
|
269
|
-
return results
|
|
270
|
-
|
|
271
|
-
npx = tree.xpath('.//div[@class="nav-link"]')
|
|
272
|
-
if not npx or not max_results:
|
|
273
|
-
return results
|
|
274
|
-
next_page = npx[-1] if isinstance(npx, list) else None
|
|
275
|
-
if isinstance(next_page, _Element):
|
|
276
|
-
names = next_page.xpath('.//input[@type="hidden"]/@name')
|
|
277
|
-
values = next_page.xpath('.//input[@type="hidden"]/@value')
|
|
278
|
-
if isinstance(names, list) and isinstance(values, list):
|
|
279
|
-
payload = {str(n): str(v) for n, v in zip(names, values)}
|
|
280
|
-
|
|
281
|
-
return results
|
|
282
|
-
|
|
283
|
-
async def _text_lite(
|
|
284
|
-
self,
|
|
285
|
-
keywords: str,
|
|
286
|
-
region: str = "wt-wt",
|
|
287
|
-
timelimit: Optional[str] = None,
|
|
288
|
-
max_results: Optional[int] = None,
|
|
289
|
-
) -> List[Dict[str, str]]:
|
|
290
|
-
"""Lite backend for text search."""
|
|
291
|
-
assert keywords, "keywords is mandatory"
|
|
292
|
-
|
|
293
|
-
payload = {
|
|
294
|
-
"q": keywords,
|
|
295
|
-
"s": "0",
|
|
296
|
-
"o": "json",
|
|
297
|
-
"api": "d.js",
|
|
298
|
-
"vqd": "",
|
|
299
|
-
"kl": region,
|
|
300
|
-
"bing_market": region,
|
|
301
|
-
}
|
|
302
|
-
if timelimit:
|
|
303
|
-
payload["df"] = timelimit
|
|
304
|
-
|
|
305
|
-
cache = set()
|
|
306
|
-
results: List[Dict[str, str]] = []
|
|
307
|
-
|
|
308
|
-
for _ in range(5):
|
|
309
|
-
resp_content = await self._get_url("POST", "https://lite.duckduckgo.com/lite/", data=payload)
|
|
310
|
-
if b"No more results." in resp_content:
|
|
311
|
-
return results
|
|
312
|
-
|
|
313
|
-
tree = document_fromstring(resp_content, self.parser)
|
|
314
|
-
elements = tree.xpath("//table[last()]//tr")
|
|
315
|
-
if not isinstance(elements, list):
|
|
316
|
-
return results
|
|
317
|
-
|
|
318
|
-
data = zip(cycle(range(1, 5)), elements)
|
|
319
|
-
for i, e in data:
|
|
320
|
-
if isinstance(e, _Element):
|
|
321
|
-
if i == 1:
|
|
322
|
-
hrefxpath = e.xpath(".//a//@href")
|
|
323
|
-
href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
|
|
324
|
-
if (
|
|
325
|
-
href is None
|
|
326
|
-
or href in cache
|
|
327
|
-
or href.startswith(
|
|
328
|
-
("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
|
|
329
|
-
)
|
|
330
|
-
):
|
|
331
|
-
[next(data, None) for _ in range(3)] # skip block(i=1,2,3,4)
|
|
332
|
-
else:
|
|
333
|
-
cache.add(href)
|
|
334
|
-
titlexpath = e.xpath(".//a//text()")
|
|
335
|
-
title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
|
|
336
|
-
elif i == 2:
|
|
337
|
-
bodyxpath = e.xpath(".//td[@class='result-snippet']//text()")
|
|
338
|
-
body = (
|
|
339
|
-
"".join(str(x) for x in bodyxpath).strip()
|
|
340
|
-
if bodyxpath and isinstance(bodyxpath, list)
|
|
341
|
-
else ""
|
|
342
|
-
)
|
|
343
|
-
if href:
|
|
344
|
-
results.append(
|
|
345
|
-
{
|
|
346
|
-
"title": _normalize(title),
|
|
347
|
-
"href": _normalize_url(href),
|
|
348
|
-
"body": _normalize(body),
|
|
349
|
-
}
|
|
350
|
-
)
|
|
351
|
-
if max_results and len(results) >= max_results:
|
|
352
|
-
return results
|
|
353
|
-
|
|
354
|
-
next_page_s = tree.xpath("//form[./input[contains(@value, 'ext')]]/input[@name='s']/@value")
|
|
355
|
-
if not next_page_s or not max_results:
|
|
356
|
-
return results
|
|
357
|
-
elif isinstance(next_page_s, list):
|
|
358
|
-
payload["s"] = str(next_page_s[0])
|
|
359
|
-
|
|
360
|
-
return results
|
|
361
|
-
|
|
362
|
-
async def aimages(
|
|
363
|
-
self,
|
|
364
|
-
keywords: str,
|
|
365
|
-
region: str = "wt-wt",
|
|
366
|
-
safesearch: str = "moderate",
|
|
367
|
-
timelimit: Optional[str] = None,
|
|
368
|
-
size: Optional[str] = None,
|
|
369
|
-
color: Optional[str] = None,
|
|
370
|
-
type_image: Optional[str] = None,
|
|
371
|
-
layout: Optional[str] = None,
|
|
372
|
-
license_image: Optional[str] = None,
|
|
373
|
-
max_results: Optional[int] = None,
|
|
374
|
-
) -> List[Dict[str, str]]:
|
|
375
|
-
"""webscout async images search. Query params: https://duckduckgo.com/params.
|
|
376
|
-
|
|
377
|
-
Args:
|
|
378
|
-
keywords: keywords for query.
|
|
379
|
-
region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
|
|
380
|
-
safesearch: on, moderate, off. Defaults to "moderate".
|
|
381
|
-
timelimit: Day, Week, Month, Year. Defaults to None.
|
|
382
|
-
size: Small, Medium, Large, Wallpaper. Defaults to None.
|
|
383
|
-
color: color, Monochrome, Red, Orange, Yellow, Green, Blue,
|
|
384
|
-
Purple, Pink, Brown, Black, Gray, Teal, White. Defaults to None.
|
|
385
|
-
type_image: photo, clipart, gif, transparent, line.
|
|
386
|
-
Defaults to None.
|
|
387
|
-
layout: Square, Tall, Wide. Defaults to None.
|
|
388
|
-
license_image: any (All Creative Commons), Public (PublicDomain),
|
|
389
|
-
Share (Free to Share and Use), ShareCommercially (Free to Share and Use Commercially),
|
|
390
|
-
Modify (Free to Modify, Share, and Use), ModifyCommercially (Free to Modify, Share, and
|
|
391
|
-
Use Commercially). Defaults to None.
|
|
392
|
-
max_results: max number of results. If None, returns results only from the first response. Defaults to None.
|
|
393
|
-
|
|
394
|
-
Returns:
|
|
395
|
-
List of dictionaries with images search results.
|
|
396
|
-
|
|
397
|
-
Raises:
|
|
398
|
-
WebscoutE: Base exception for webscout errors.
|
|
399
|
-
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
400
|
-
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
401
|
-
"""
|
|
402
|
-
result = await self._loop.run_in_executor(
|
|
403
|
-
self._executor,
|
|
404
|
-
super().images,
|
|
405
|
-
keywords,
|
|
406
|
-
region,
|
|
407
|
-
safesearch,
|
|
408
|
-
timelimit,
|
|
409
|
-
size,
|
|
410
|
-
color,
|
|
411
|
-
type_image,
|
|
412
|
-
layout,
|
|
413
|
-
license_image,
|
|
414
|
-
max_results,
|
|
415
|
-
)
|
|
416
|
-
return result
|
|
417
|
-
|
|
418
|
-
async def avideos(
|
|
419
|
-
self,
|
|
420
|
-
keywords: str,
|
|
421
|
-
region: str = "wt-wt",
|
|
422
|
-
safesearch: str = "moderate",
|
|
423
|
-
timelimit: Optional[str] = None,
|
|
424
|
-
resolution: Optional[str] = None,
|
|
425
|
-
duration: Optional[str] = None,
|
|
426
|
-
license_videos: Optional[str] = None,
|
|
427
|
-
max_results: Optional[int] = None,
|
|
428
|
-
) -> List[Dict[str, str]]:
|
|
429
|
-
"""webscout async videos search. Query params: https://duckduckgo.com/params.
|
|
430
|
-
|
|
431
|
-
Args:
|
|
432
|
-
keywords: keywords for query.
|
|
433
|
-
region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
|
|
434
|
-
safesearch: on, moderate, off. Defaults to "moderate".
|
|
435
|
-
timelimit: d, w, m. Defaults to None.
|
|
436
|
-
resolution: high, standart. Defaults to None.
|
|
437
|
-
duration: short, medium, long. Defaults to None.
|
|
438
|
-
license_videos: creativeCommon, youtube. Defaults to None.
|
|
439
|
-
max_results: max number of results. If None, returns results only from the first response. Defaults to None.
|
|
440
|
-
|
|
441
|
-
Returns:
|
|
442
|
-
List of dictionaries with videos search results.
|
|
443
|
-
|
|
444
|
-
Raises:
|
|
445
|
-
WebscoutE: Base exception for webscout errors.
|
|
446
|
-
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
447
|
-
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
448
|
-
"""
|
|
449
|
-
result = await self._loop.run_in_executor(
|
|
450
|
-
self._executor,
|
|
451
|
-
super().videos,
|
|
452
|
-
keywords,
|
|
453
|
-
region,
|
|
454
|
-
safesearch,
|
|
455
|
-
timelimit,
|
|
456
|
-
resolution,
|
|
457
|
-
duration,
|
|
458
|
-
license_videos,
|
|
459
|
-
max_results,
|
|
460
|
-
)
|
|
461
|
-
return result
|
|
462
|
-
|
|
463
|
-
async def anews(
|
|
464
|
-
self,
|
|
465
|
-
keywords: str,
|
|
466
|
-
region: str = "wt-wt",
|
|
467
|
-
safesearch: str = "moderate",
|
|
468
|
-
timelimit: Optional[str] = None,
|
|
469
|
-
max_results: Optional[int] = None,
|
|
470
|
-
) -> List[Dict[str, str]]:
|
|
471
|
-
"""webscout async news search. Query params: https://duckduckgo.com/params.
|
|
472
|
-
|
|
473
|
-
Args:
|
|
474
|
-
keywords: keywords for query.
|
|
475
|
-
region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
|
|
476
|
-
safesearch: on, moderate, off. Defaults to "moderate".
|
|
477
|
-
timelimit: d, w, m. Defaults to None.
|
|
478
|
-
max_results: max number of results. If None, returns results only from the first response. Defaults to None.
|
|
479
|
-
|
|
480
|
-
Returns:
|
|
481
|
-
List of dictionaries with news search results.
|
|
482
|
-
|
|
483
|
-
Raises:
|
|
484
|
-
WebscoutE: Base exception for webscout errors.
|
|
485
|
-
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
486
|
-
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
487
|
-
"""
|
|
488
|
-
result = await self._loop.run_in_executor(
|
|
489
|
-
self._executor,
|
|
490
|
-
super().news,
|
|
491
|
-
keywords,
|
|
492
|
-
region,
|
|
493
|
-
safesearch,
|
|
494
|
-
timelimit,
|
|
495
|
-
max_results,
|
|
496
|
-
)
|
|
497
|
-
return result
|
|
498
|
-
|
|
499
|
-
async def aanswers(
|
|
500
|
-
self,
|
|
501
|
-
keywords: str,
|
|
502
|
-
) -> List[Dict[str, str]]:
|
|
503
|
-
"""webscout async instant answers. Query params: https://duckduckgo.com/params.
|
|
504
|
-
|
|
505
|
-
Args:
|
|
506
|
-
keywords: keywords for query,
|
|
507
|
-
|
|
508
|
-
Returns:
|
|
509
|
-
List of dictionaries with instant answers results.
|
|
510
|
-
|
|
511
|
-
Raises:
|
|
512
|
-
WebscoutE: Base exception for webscout errors.
|
|
513
|
-
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
514
|
-
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
515
|
-
"""
|
|
516
|
-
result = await self._loop.run_in_executor(
|
|
517
|
-
self._executor,
|
|
518
|
-
super().answers,
|
|
519
|
-
keywords,
|
|
520
|
-
)
|
|
521
|
-
return result
|
|
522
|
-
|
|
523
|
-
async def asuggestions(
|
|
524
|
-
self,
|
|
525
|
-
keywords: str,
|
|
526
|
-
region: str = "wt-wt",
|
|
527
|
-
) -> List[Dict[str, str]]:
|
|
528
|
-
"""webscout async suggestions. Query params: https://duckduckgo.com/params.
|
|
529
|
-
|
|
530
|
-
Args:
|
|
531
|
-
keywords: keywords for query.
|
|
532
|
-
region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
|
|
533
|
-
|
|
534
|
-
Returns:
|
|
535
|
-
List of dictionaries with suggestions results.
|
|
536
|
-
|
|
537
|
-
Raises:
|
|
538
|
-
WebscoutE: Base exception for webscout errors.
|
|
539
|
-
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
540
|
-
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
541
|
-
"""
|
|
542
|
-
result = await self._loop.run_in_executor(
|
|
543
|
-
self._executor,
|
|
544
|
-
super().suggestions,
|
|
545
|
-
keywords,
|
|
546
|
-
region,
|
|
547
|
-
)
|
|
548
|
-
return result
|
|
549
|
-
|
|
550
|
-
async def amaps(
|
|
551
|
-
self,
|
|
552
|
-
keywords: str,
|
|
553
|
-
place: Optional[str] = None,
|
|
554
|
-
street: Optional[str] = None,
|
|
555
|
-
city: Optional[str] = None,
|
|
556
|
-
county: Optional[str] = None,
|
|
557
|
-
state: Optional[str] = None,
|
|
558
|
-
country: Optional[str] = None,
|
|
559
|
-
postalcode: Optional[str] = None,
|
|
560
|
-
latitude: Optional[str] = None,
|
|
561
|
-
longitude: Optional[str] = None,
|
|
562
|
-
radius: int = 0,
|
|
563
|
-
max_results: Optional[int] = None,
|
|
564
|
-
) -> List[Dict[str, str]]:
|
|
565
|
-
"""webscout async maps search. Query params: https://duckduckgo.com/params.
|
|
566
|
-
|
|
567
|
-
Args:
|
|
568
|
-
keywords: keywords for query
|
|
569
|
-
place: if set, the other parameters are not used. Defaults to None.
|
|
570
|
-
street: house number/street. Defaults to None.
|
|
571
|
-
city: city of search. Defaults to None.
|
|
572
|
-
county: county of search. Defaults to None.
|
|
573
|
-
state: state of search. Defaults to None.
|
|
574
|
-
country: country of search. Defaults to None.
|
|
575
|
-
postalcode: postalcode of search. Defaults to None.
|
|
576
|
-
latitude: geographic coordinate (north-south position). Defaults to None.
|
|
577
|
-
longitude: geographic coordinate (east-west position); if latitude and
|
|
578
|
-
longitude are set, the other parameters are not used. Defaults to None.
|
|
579
|
-
radius: expand the search square by the distance in kilometers. Defaults to 0.
|
|
580
|
-
max_results: max number of results. If None, returns results only from the first response. Defaults to None.
|
|
581
|
-
|
|
582
|
-
Returns:
|
|
583
|
-
List of dictionaries with maps search results, or None if there was an error.
|
|
584
|
-
|
|
585
|
-
Raises:
|
|
586
|
-
WebscoutE: Base exception for webscout errors.
|
|
587
|
-
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
588
|
-
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
589
|
-
"""
|
|
590
|
-
result = await self._loop.run_in_executor(
|
|
591
|
-
self._executor,
|
|
592
|
-
super().maps,
|
|
593
|
-
keywords,
|
|
594
|
-
place,
|
|
595
|
-
street,
|
|
596
|
-
city,
|
|
597
|
-
county,
|
|
598
|
-
state,
|
|
599
|
-
country,
|
|
600
|
-
postalcode,
|
|
601
|
-
latitude,
|
|
602
|
-
longitude,
|
|
603
|
-
radius,
|
|
604
|
-
max_results,
|
|
605
|
-
)
|
|
606
|
-
return result
|
|
607
|
-
|
|
608
|
-
async def atranslate(
|
|
609
|
-
self,
|
|
610
|
-
keywords: Union[List[str], str],
|
|
611
|
-
from_: Optional[str] = None,
|
|
612
|
-
to: str = "en",
|
|
613
|
-
) -> List[Dict[str, str]]:
|
|
614
|
-
"""webscout async translate.
|
|
615
|
-
|
|
616
|
-
Args:
|
|
617
|
-
keywords: string or list of strings to translate.
|
|
618
|
-
from_: translate from (defaults automatically). Defaults to None.
|
|
619
|
-
to: what language to translate. Defaults to "en".
|
|
620
|
-
|
|
621
|
-
Returns:
|
|
622
|
-
List od dictionaries with translated keywords.
|
|
623
|
-
|
|
624
|
-
Raises:
|
|
625
|
-
WebscoutE: Base exception for webscout errors.
|
|
626
|
-
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
627
|
-
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
628
|
-
"""
|
|
629
|
-
result = await self._loop.run_in_executor(
|
|
630
|
-
self._executor,
|
|
631
|
-
super().translate,
|
|
632
|
-
keywords,
|
|
633
|
-
from_,
|
|
634
|
-
to,
|
|
635
|
-
)
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import warnings
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from functools import cached_property
|
|
9
|
+
from itertools import cycle
|
|
10
|
+
from random import choice, shuffle
|
|
11
|
+
from time import time
|
|
12
|
+
from types import TracebackType
|
|
13
|
+
from typing import Any, Dict, List, Optional, Type, Union, cast
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
from lxml.etree import _Element
|
|
17
|
+
from lxml.html import HTMLParser as LHTMLParser
|
|
18
|
+
from lxml.html import document_fromstring
|
|
19
|
+
|
|
20
|
+
from .exceptions import RatelimitE, TimeoutE, WebscoutE
|
|
21
|
+
from .utils import (
|
|
22
|
+
_expand_proxy_tb_alias,
|
|
23
|
+
_extract_vqd,
|
|
24
|
+
_normalize,
|
|
25
|
+
_normalize_url,
|
|
26
|
+
json_loads,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger("webscout.AsyncWEBS")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AsyncWEBS:
|
|
33
|
+
"""Asynchronous webscout class to get search results."""
|
|
34
|
+
|
|
35
|
+
_impersonates = (
|
|
36
|
+
"chrome_100", "chrome_101", "chrome_104", "chrome_105", "chrome_106", "chrome_107",
|
|
37
|
+
"chrome_108", "chrome_109", "chrome_114", "chrome_116", "chrome_117", "chrome_118",
|
|
38
|
+
"chrome_119", "chrome_120", "chrome_123", "chrome_124", "chrome_126", "chrome_127",
|
|
39
|
+
"chrome_128", "chrome_129", "chrome_130", "chrome_131",
|
|
40
|
+
"safari_ios_16.5", "safari_ios_17.2", "safari_ios_17.4.1", "safari_ios_18.1.1",
|
|
41
|
+
"safari_15.3", "safari_15.5", "safari_15.6.1", "safari_16", "safari_16.5",
|
|
42
|
+
"safari_17.0", "safari_17.2.1", "safari_17.4.1", "safari_17.5",
|
|
43
|
+
"safari_18", "safari_18.2",
|
|
44
|
+
"safari_ipad_18",
|
|
45
|
+
"edge_101", "edge_122", "edge_127", "edge_131",
|
|
46
|
+
"firefox_109", "firefox_117", "firefox_128", "firefox_133",
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
headers: Optional[Dict[str, str]] = None,
|
|
52
|
+
proxy: Optional[str] = None,
|
|
53
|
+
proxies: Union[Dict[str, str], str, None] = None, # deprecated
|
|
54
|
+
timeout: Optional[int] = 10,
|
|
55
|
+
) -> None:
|
|
56
|
+
"""Initialize the AsyncWEBS object.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
headers (dict, optional): Dictionary of headers for the HTTP client. Defaults to None.
|
|
60
|
+
proxy (str, optional): proxy for the HTTP client, supports http/https/socks5 protocols.
|
|
61
|
+
example: "http://user:pass@example.com:3128". Defaults to None.
|
|
62
|
+
timeout (int, optional): Timeout value for the HTTP client. Defaults to 10.
|
|
63
|
+
"""
|
|
64
|
+
self.proxy: Optional[str] = _expand_proxy_tb_alias(proxy)
|
|
65
|
+
assert self.proxy is None or isinstance(self.proxy, str), "proxy must be a str"
|
|
66
|
+
if not proxy and proxies:
|
|
67
|
+
warnings.warn("'proxies' is deprecated, use 'proxy' instead.", stacklevel=1)
|
|
68
|
+
self.proxy = proxies.get("http") or proxies.get("https") if isinstance(proxies, dict) else proxies
|
|
69
|
+
|
|
70
|
+
default_headers = {
|
|
71
|
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
|
72
|
+
"Accept-Language": "en-US,en;q=0.5",
|
|
73
|
+
"Accept-Encoding": "gzip, deflate, br",
|
|
74
|
+
"DNT": "1",
|
|
75
|
+
"Connection": "keep-alive",
|
|
76
|
+
"Upgrade-Insecure-Requests": "1",
|
|
77
|
+
"Sec-Fetch-Dest": "document",
|
|
78
|
+
"Sec-Fetch-Mode": "navigate",
|
|
79
|
+
"Sec-Fetch-Site": "none",
|
|
80
|
+
"Sec-Fetch-User": "?1",
|
|
81
|
+
"Referer": "https://duckduckgo.com/",
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
self.headers = headers if headers else {}
|
|
85
|
+
self.headers.update(default_headers)
|
|
86
|
+
|
|
87
|
+
self.client = httpx.AsyncClient(
|
|
88
|
+
headers=self.headers,
|
|
89
|
+
proxies=self.proxy,
|
|
90
|
+
timeout=timeout,
|
|
91
|
+
follow_redirects=True,
|
|
92
|
+
verify=False,
|
|
93
|
+
)
|
|
94
|
+
self.sleep_timestamp = 0.0
|
|
95
|
+
|
|
96
|
+
async def __aenter__(self) -> AsyncWEBS:
|
|
97
|
+
return self
|
|
98
|
+
|
|
99
|
+
async def __aexit__(
|
|
100
|
+
self,
|
|
101
|
+
exc_type: Optional[Type[BaseException]] = None,
|
|
102
|
+
exc_val: Optional[BaseException] = None,
|
|
103
|
+
exc_tb: Optional[TracebackType] = None,
|
|
104
|
+
) -> None:
|
|
105
|
+
await self.client.aclose()
|
|
106
|
+
|
|
107
|
+
@cached_property
|
|
108
|
+
def parser(self) -> LHTMLParser:
|
|
109
|
+
"""Get HTML parser."""
|
|
110
|
+
return LHTMLParser(remove_blank_text=True, remove_comments=True, remove_pis=True, collect_ids=False)
|
|
111
|
+
|
|
112
|
+
async def _sleep(self, sleeptime: float = 2.0) -> None:
|
|
113
|
+
"""Sleep between API requests."""
|
|
114
|
+
delay = sleeptime if not self.sleep_timestamp else sleeptime if time() - self.sleep_timestamp >= 30 else sleeptime * 2
|
|
115
|
+
self.sleep_timestamp = time()
|
|
116
|
+
await asyncio.sleep(delay)
|
|
117
|
+
|
|
118
|
+
async def _get_url(
|
|
119
|
+
self,
|
|
120
|
+
method: str,
|
|
121
|
+
url: str,
|
|
122
|
+
params: Optional[Dict[str, str]] = None,
|
|
123
|
+
content: Optional[bytes] = None,
|
|
124
|
+
data: Optional[Dict[str, str]] = None,
|
|
125
|
+
) -> bytes:
|
|
126
|
+
"""Make HTTP request with proper rate limiting."""
|
|
127
|
+
await self._sleep()
|
|
128
|
+
try:
|
|
129
|
+
resp = await self.client.request(method, url, params=params, content=content, data=data)
|
|
130
|
+
|
|
131
|
+
# Add additional delay if we get a 429 or similar status
|
|
132
|
+
if resp.status_code in (429, 403, 503):
|
|
133
|
+
await asyncio.sleep(5.0) # Additional delay for rate limit responses
|
|
134
|
+
resp = await self.client.request(method, url, params=params, content=content, data=data)
|
|
135
|
+
|
|
136
|
+
except Exception as ex:
|
|
137
|
+
if "time" in str(ex).lower():
|
|
138
|
+
raise TimeoutE(f"{url} {type(ex).__name__}: {ex}") from ex
|
|
139
|
+
raise WebscoutE(f"{url} {type(ex).__name__}: {ex}") from ex
|
|
140
|
+
|
|
141
|
+
if resp.status_code == 200:
|
|
142
|
+
return resp.content
|
|
143
|
+
elif resp.status_code in (202, 301, 403, 429, 503):
|
|
144
|
+
raise RatelimitE(f"{url} {resp.status_code} Ratelimit - Please wait a few minutes before retrying")
|
|
145
|
+
raise WebscoutE(f"{url} return None. {params=} {content=} {data=}")
|
|
146
|
+
|
|
147
|
+
async def achat(self, keywords: str, model: str = "gpt-4o-mini") -> str:
|
|
148
|
+
"""Initiates async chat session with webscout AI.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
keywords (str): The initial message or question to send to the AI.
|
|
152
|
+
model (str): The model to use: "gpt-4o-mini", "claude-3-haiku", "llama-3-70b", "mixtral-8x7b", "o3-mini".
|
|
153
|
+
Defaults to "gpt-4o-mini".
|
|
154
|
+
|
|
155
|
+
Returns:
|
|
156
|
+
str: The response from the AI.
|
|
157
|
+
"""
|
|
158
|
+
result = await self._loop.run_in_executor(self._executor, super().chat, keywords, model)
|
|
159
|
+
return result
|
|
160
|
+
|
|
161
|
+
async def atext(
|
|
162
|
+
self,
|
|
163
|
+
keywords: str,
|
|
164
|
+
region: str = "wt-wt",
|
|
165
|
+
safesearch: str = "moderate",
|
|
166
|
+
timelimit: Optional[str] = None,
|
|
167
|
+
backend: str = "auto",
|
|
168
|
+
max_results: Optional[int] = None,
|
|
169
|
+
) -> List[Dict[str, str]]:
|
|
170
|
+
"""webscout async text search. Query params: https://duckduckgo.com/params.
|
|
171
|
+
|
|
172
|
+
Args:
|
|
173
|
+
keywords: keywords for query.
|
|
174
|
+
region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
|
|
175
|
+
safesearch: on, moderate, off. Defaults to "moderate".
|
|
176
|
+
timelimit: d, w, m, y. Defaults to None.
|
|
177
|
+
backend: auto, html, lite. Defaults to auto.
|
|
178
|
+
auto - try all backends in random order,
|
|
179
|
+
html - collect data from https://html.duckduckgo.com,
|
|
180
|
+
lite - collect data from https://lite.duckduckgo.com.
|
|
181
|
+
max_results: max number of results. If None, returns results only from the first response. Defaults to None.
|
|
182
|
+
|
|
183
|
+
Returns:
|
|
184
|
+
List of dictionaries with search results.
|
|
185
|
+
|
|
186
|
+
Raises:
|
|
187
|
+
WebscoutE: Base exception for webscout errors.
|
|
188
|
+
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
189
|
+
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
190
|
+
"""
|
|
191
|
+
if backend in ("api", "ecosia"):
|
|
192
|
+
warnings.warn(f"{backend=} is deprecated, using backend='auto'", stacklevel=2)
|
|
193
|
+
backend = "auto"
|
|
194
|
+
backends = ["html", "lite"] if backend == "auto" else [backend]
|
|
195
|
+
shuffle(backends)
|
|
196
|
+
|
|
197
|
+
results, err = [], None
|
|
198
|
+
for b in backends:
|
|
199
|
+
try:
|
|
200
|
+
if b == "html":
|
|
201
|
+
results = await self._text_html(keywords, region, timelimit, max_results)
|
|
202
|
+
elif b == "lite":
|
|
203
|
+
results = await self._text_lite(keywords, region, timelimit, max_results)
|
|
204
|
+
return results
|
|
205
|
+
except Exception as ex:
|
|
206
|
+
err = ex
|
|
207
|
+
|
|
208
|
+
raise WebscoutE(err)
|
|
209
|
+
|
|
210
|
+
async def _text_html(
|
|
211
|
+
self,
|
|
212
|
+
keywords: str,
|
|
213
|
+
region: str = "wt-wt",
|
|
214
|
+
timelimit: Optional[str] = None,
|
|
215
|
+
max_results: Optional[int] = None,
|
|
216
|
+
) -> List[Dict[str, str]]:
|
|
217
|
+
"""HTML backend for text search."""
|
|
218
|
+
assert keywords, "keywords is mandatory"
|
|
219
|
+
|
|
220
|
+
payload = {
|
|
221
|
+
"q": keywords,
|
|
222
|
+
"s": "0",
|
|
223
|
+
"o": "json",
|
|
224
|
+
"api": "d.js",
|
|
225
|
+
"vqd": "",
|
|
226
|
+
"kl": region,
|
|
227
|
+
"bing_market": region,
|
|
228
|
+
}
|
|
229
|
+
if timelimit:
|
|
230
|
+
payload["df"] = timelimit
|
|
231
|
+
|
|
232
|
+
cache = set()
|
|
233
|
+
results: List[Dict[str, str]] = []
|
|
234
|
+
|
|
235
|
+
for _ in range(5):
|
|
236
|
+
resp_content = await self._get_url("POST", "https://html.duckduckgo.com/html", data=payload)
|
|
237
|
+
if b"No results." in resp_content:
|
|
238
|
+
return results
|
|
239
|
+
|
|
240
|
+
tree = document_fromstring(resp_content, self.parser)
|
|
241
|
+
elements = tree.xpath("//div[h2]")
|
|
242
|
+
if not isinstance(elements, list):
|
|
243
|
+
return results
|
|
244
|
+
|
|
245
|
+
for e in elements:
|
|
246
|
+
if isinstance(e, _Element):
|
|
247
|
+
hrefxpath = e.xpath("./a/@href")
|
|
248
|
+
href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
|
|
249
|
+
if (
|
|
250
|
+
href
|
|
251
|
+
and href not in cache
|
|
252
|
+
and not href.startswith(
|
|
253
|
+
("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
|
|
254
|
+
)
|
|
255
|
+
):
|
|
256
|
+
cache.add(href)
|
|
257
|
+
titlexpath = e.xpath("./h2/a/text()")
|
|
258
|
+
title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
|
|
259
|
+
bodyxpath = e.xpath("./a//text()")
|
|
260
|
+
body = "".join(str(x) for x in bodyxpath) if bodyxpath and isinstance(bodyxpath, list) else ""
|
|
261
|
+
results.append(
|
|
262
|
+
{
|
|
263
|
+
"title": _normalize(title),
|
|
264
|
+
"href": _normalize_url(href),
|
|
265
|
+
"body": _normalize(body),
|
|
266
|
+
}
|
|
267
|
+
)
|
|
268
|
+
if max_results and len(results) >= max_results:
|
|
269
|
+
return results
|
|
270
|
+
|
|
271
|
+
npx = tree.xpath('.//div[@class="nav-link"]')
|
|
272
|
+
if not npx or not max_results:
|
|
273
|
+
return results
|
|
274
|
+
next_page = npx[-1] if isinstance(npx, list) else None
|
|
275
|
+
if isinstance(next_page, _Element):
|
|
276
|
+
names = next_page.xpath('.//input[@type="hidden"]/@name')
|
|
277
|
+
values = next_page.xpath('.//input[@type="hidden"]/@value')
|
|
278
|
+
if isinstance(names, list) and isinstance(values, list):
|
|
279
|
+
payload = {str(n): str(v) for n, v in zip(names, values)}
|
|
280
|
+
|
|
281
|
+
return results
|
|
282
|
+
|
|
283
|
+
async def _text_lite(
|
|
284
|
+
self,
|
|
285
|
+
keywords: str,
|
|
286
|
+
region: str = "wt-wt",
|
|
287
|
+
timelimit: Optional[str] = None,
|
|
288
|
+
max_results: Optional[int] = None,
|
|
289
|
+
) -> List[Dict[str, str]]:
|
|
290
|
+
"""Lite backend for text search."""
|
|
291
|
+
assert keywords, "keywords is mandatory"
|
|
292
|
+
|
|
293
|
+
payload = {
|
|
294
|
+
"q": keywords,
|
|
295
|
+
"s": "0",
|
|
296
|
+
"o": "json",
|
|
297
|
+
"api": "d.js",
|
|
298
|
+
"vqd": "",
|
|
299
|
+
"kl": region,
|
|
300
|
+
"bing_market": region,
|
|
301
|
+
}
|
|
302
|
+
if timelimit:
|
|
303
|
+
payload["df"] = timelimit
|
|
304
|
+
|
|
305
|
+
cache = set()
|
|
306
|
+
results: List[Dict[str, str]] = []
|
|
307
|
+
|
|
308
|
+
for _ in range(5):
|
|
309
|
+
resp_content = await self._get_url("POST", "https://lite.duckduckgo.com/lite/", data=payload)
|
|
310
|
+
if b"No more results." in resp_content:
|
|
311
|
+
return results
|
|
312
|
+
|
|
313
|
+
tree = document_fromstring(resp_content, self.parser)
|
|
314
|
+
elements = tree.xpath("//table[last()]//tr")
|
|
315
|
+
if not isinstance(elements, list):
|
|
316
|
+
return results
|
|
317
|
+
|
|
318
|
+
data = zip(cycle(range(1, 5)), elements)
|
|
319
|
+
for i, e in data:
|
|
320
|
+
if isinstance(e, _Element):
|
|
321
|
+
if i == 1:
|
|
322
|
+
hrefxpath = e.xpath(".//a//@href")
|
|
323
|
+
href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
|
|
324
|
+
if (
|
|
325
|
+
href is None
|
|
326
|
+
or href in cache
|
|
327
|
+
or href.startswith(
|
|
328
|
+
("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
|
|
329
|
+
)
|
|
330
|
+
):
|
|
331
|
+
[next(data, None) for _ in range(3)] # skip block(i=1,2,3,4)
|
|
332
|
+
else:
|
|
333
|
+
cache.add(href)
|
|
334
|
+
titlexpath = e.xpath(".//a//text()")
|
|
335
|
+
title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
|
|
336
|
+
elif i == 2:
|
|
337
|
+
bodyxpath = e.xpath(".//td[@class='result-snippet']//text()")
|
|
338
|
+
body = (
|
|
339
|
+
"".join(str(x) for x in bodyxpath).strip()
|
|
340
|
+
if bodyxpath and isinstance(bodyxpath, list)
|
|
341
|
+
else ""
|
|
342
|
+
)
|
|
343
|
+
if href:
|
|
344
|
+
results.append(
|
|
345
|
+
{
|
|
346
|
+
"title": _normalize(title),
|
|
347
|
+
"href": _normalize_url(href),
|
|
348
|
+
"body": _normalize(body),
|
|
349
|
+
}
|
|
350
|
+
)
|
|
351
|
+
if max_results and len(results) >= max_results:
|
|
352
|
+
return results
|
|
353
|
+
|
|
354
|
+
next_page_s = tree.xpath("//form[./input[contains(@value, 'ext')]]/input[@name='s']/@value")
|
|
355
|
+
if not next_page_s or not max_results:
|
|
356
|
+
return results
|
|
357
|
+
elif isinstance(next_page_s, list):
|
|
358
|
+
payload["s"] = str(next_page_s[0])
|
|
359
|
+
|
|
360
|
+
return results
|
|
361
|
+
|
|
362
|
+
async def aimages(
|
|
363
|
+
self,
|
|
364
|
+
keywords: str,
|
|
365
|
+
region: str = "wt-wt",
|
|
366
|
+
safesearch: str = "moderate",
|
|
367
|
+
timelimit: Optional[str] = None,
|
|
368
|
+
size: Optional[str] = None,
|
|
369
|
+
color: Optional[str] = None,
|
|
370
|
+
type_image: Optional[str] = None,
|
|
371
|
+
layout: Optional[str] = None,
|
|
372
|
+
license_image: Optional[str] = None,
|
|
373
|
+
max_results: Optional[int] = None,
|
|
374
|
+
) -> List[Dict[str, str]]:
|
|
375
|
+
"""webscout async images search. Query params: https://duckduckgo.com/params.
|
|
376
|
+
|
|
377
|
+
Args:
|
|
378
|
+
keywords: keywords for query.
|
|
379
|
+
region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
|
|
380
|
+
safesearch: on, moderate, off. Defaults to "moderate".
|
|
381
|
+
timelimit: Day, Week, Month, Year. Defaults to None.
|
|
382
|
+
size: Small, Medium, Large, Wallpaper. Defaults to None.
|
|
383
|
+
color: color, Monochrome, Red, Orange, Yellow, Green, Blue,
|
|
384
|
+
Purple, Pink, Brown, Black, Gray, Teal, White. Defaults to None.
|
|
385
|
+
type_image: photo, clipart, gif, transparent, line.
|
|
386
|
+
Defaults to None.
|
|
387
|
+
layout: Square, Tall, Wide. Defaults to None.
|
|
388
|
+
license_image: any (All Creative Commons), Public (PublicDomain),
|
|
389
|
+
Share (Free to Share and Use), ShareCommercially (Free to Share and Use Commercially),
|
|
390
|
+
Modify (Free to Modify, Share, and Use), ModifyCommercially (Free to Modify, Share, and
|
|
391
|
+
Use Commercially). Defaults to None.
|
|
392
|
+
max_results: max number of results. If None, returns results only from the first response. Defaults to None.
|
|
393
|
+
|
|
394
|
+
Returns:
|
|
395
|
+
List of dictionaries with images search results.
|
|
396
|
+
|
|
397
|
+
Raises:
|
|
398
|
+
WebscoutE: Base exception for webscout errors.
|
|
399
|
+
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
400
|
+
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
401
|
+
"""
|
|
402
|
+
result = await self._loop.run_in_executor(
|
|
403
|
+
self._executor,
|
|
404
|
+
super().images,
|
|
405
|
+
keywords,
|
|
406
|
+
region,
|
|
407
|
+
safesearch,
|
|
408
|
+
timelimit,
|
|
409
|
+
size,
|
|
410
|
+
color,
|
|
411
|
+
type_image,
|
|
412
|
+
layout,
|
|
413
|
+
license_image,
|
|
414
|
+
max_results,
|
|
415
|
+
)
|
|
416
|
+
return result
|
|
417
|
+
|
|
418
|
+
async def avideos(
|
|
419
|
+
self,
|
|
420
|
+
keywords: str,
|
|
421
|
+
region: str = "wt-wt",
|
|
422
|
+
safesearch: str = "moderate",
|
|
423
|
+
timelimit: Optional[str] = None,
|
|
424
|
+
resolution: Optional[str] = None,
|
|
425
|
+
duration: Optional[str] = None,
|
|
426
|
+
license_videos: Optional[str] = None,
|
|
427
|
+
max_results: Optional[int] = None,
|
|
428
|
+
) -> List[Dict[str, str]]:
|
|
429
|
+
"""webscout async videos search. Query params: https://duckduckgo.com/params.
|
|
430
|
+
|
|
431
|
+
Args:
|
|
432
|
+
keywords: keywords for query.
|
|
433
|
+
region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
|
|
434
|
+
safesearch: on, moderate, off. Defaults to "moderate".
|
|
435
|
+
timelimit: d, w, m. Defaults to None.
|
|
436
|
+
resolution: high, standart. Defaults to None.
|
|
437
|
+
duration: short, medium, long. Defaults to None.
|
|
438
|
+
license_videos: creativeCommon, youtube. Defaults to None.
|
|
439
|
+
max_results: max number of results. If None, returns results only from the first response. Defaults to None.
|
|
440
|
+
|
|
441
|
+
Returns:
|
|
442
|
+
List of dictionaries with videos search results.
|
|
443
|
+
|
|
444
|
+
Raises:
|
|
445
|
+
WebscoutE: Base exception for webscout errors.
|
|
446
|
+
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
447
|
+
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
448
|
+
"""
|
|
449
|
+
result = await self._loop.run_in_executor(
|
|
450
|
+
self._executor,
|
|
451
|
+
super().videos,
|
|
452
|
+
keywords,
|
|
453
|
+
region,
|
|
454
|
+
safesearch,
|
|
455
|
+
timelimit,
|
|
456
|
+
resolution,
|
|
457
|
+
duration,
|
|
458
|
+
license_videos,
|
|
459
|
+
max_results,
|
|
460
|
+
)
|
|
461
|
+
return result
|
|
462
|
+
|
|
463
|
+
async def anews(
|
|
464
|
+
self,
|
|
465
|
+
keywords: str,
|
|
466
|
+
region: str = "wt-wt",
|
|
467
|
+
safesearch: str = "moderate",
|
|
468
|
+
timelimit: Optional[str] = None,
|
|
469
|
+
max_results: Optional[int] = None,
|
|
470
|
+
) -> List[Dict[str, str]]:
|
|
471
|
+
"""webscout async news search. Query params: https://duckduckgo.com/params.
|
|
472
|
+
|
|
473
|
+
Args:
|
|
474
|
+
keywords: keywords for query.
|
|
475
|
+
region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
|
|
476
|
+
safesearch: on, moderate, off. Defaults to "moderate".
|
|
477
|
+
timelimit: d, w, m. Defaults to None.
|
|
478
|
+
max_results: max number of results. If None, returns results only from the first response. Defaults to None.
|
|
479
|
+
|
|
480
|
+
Returns:
|
|
481
|
+
List of dictionaries with news search results.
|
|
482
|
+
|
|
483
|
+
Raises:
|
|
484
|
+
WebscoutE: Base exception for webscout errors.
|
|
485
|
+
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
486
|
+
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
487
|
+
"""
|
|
488
|
+
result = await self._loop.run_in_executor(
|
|
489
|
+
self._executor,
|
|
490
|
+
super().news,
|
|
491
|
+
keywords,
|
|
492
|
+
region,
|
|
493
|
+
safesearch,
|
|
494
|
+
timelimit,
|
|
495
|
+
max_results,
|
|
496
|
+
)
|
|
497
|
+
return result
|
|
498
|
+
|
|
499
|
+
async def aanswers(
|
|
500
|
+
self,
|
|
501
|
+
keywords: str,
|
|
502
|
+
) -> List[Dict[str, str]]:
|
|
503
|
+
"""webscout async instant answers. Query params: https://duckduckgo.com/params.
|
|
504
|
+
|
|
505
|
+
Args:
|
|
506
|
+
keywords: keywords for query,
|
|
507
|
+
|
|
508
|
+
Returns:
|
|
509
|
+
List of dictionaries with instant answers results.
|
|
510
|
+
|
|
511
|
+
Raises:
|
|
512
|
+
WebscoutE: Base exception for webscout errors.
|
|
513
|
+
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
514
|
+
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
515
|
+
"""
|
|
516
|
+
result = await self._loop.run_in_executor(
|
|
517
|
+
self._executor,
|
|
518
|
+
super().answers,
|
|
519
|
+
keywords,
|
|
520
|
+
)
|
|
521
|
+
return result
|
|
522
|
+
|
|
523
|
+
async def asuggestions(
|
|
524
|
+
self,
|
|
525
|
+
keywords: str,
|
|
526
|
+
region: str = "wt-wt",
|
|
527
|
+
) -> List[Dict[str, str]]:
|
|
528
|
+
"""webscout async suggestions. Query params: https://duckduckgo.com/params.
|
|
529
|
+
|
|
530
|
+
Args:
|
|
531
|
+
keywords: keywords for query.
|
|
532
|
+
region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
|
|
533
|
+
|
|
534
|
+
Returns:
|
|
535
|
+
List of dictionaries with suggestions results.
|
|
536
|
+
|
|
537
|
+
Raises:
|
|
538
|
+
WebscoutE: Base exception for webscout errors.
|
|
539
|
+
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
540
|
+
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
541
|
+
"""
|
|
542
|
+
result = await self._loop.run_in_executor(
|
|
543
|
+
self._executor,
|
|
544
|
+
super().suggestions,
|
|
545
|
+
keywords,
|
|
546
|
+
region,
|
|
547
|
+
)
|
|
548
|
+
return result
|
|
549
|
+
|
|
550
|
+
async def amaps(
|
|
551
|
+
self,
|
|
552
|
+
keywords: str,
|
|
553
|
+
place: Optional[str] = None,
|
|
554
|
+
street: Optional[str] = None,
|
|
555
|
+
city: Optional[str] = None,
|
|
556
|
+
county: Optional[str] = None,
|
|
557
|
+
state: Optional[str] = None,
|
|
558
|
+
country: Optional[str] = None,
|
|
559
|
+
postalcode: Optional[str] = None,
|
|
560
|
+
latitude: Optional[str] = None,
|
|
561
|
+
longitude: Optional[str] = None,
|
|
562
|
+
radius: int = 0,
|
|
563
|
+
max_results: Optional[int] = None,
|
|
564
|
+
) -> List[Dict[str, str]]:
|
|
565
|
+
"""webscout async maps search. Query params: https://duckduckgo.com/params.
|
|
566
|
+
|
|
567
|
+
Args:
|
|
568
|
+
keywords: keywords for query
|
|
569
|
+
place: if set, the other parameters are not used. Defaults to None.
|
|
570
|
+
street: house number/street. Defaults to None.
|
|
571
|
+
city: city of search. Defaults to None.
|
|
572
|
+
county: county of search. Defaults to None.
|
|
573
|
+
state: state of search. Defaults to None.
|
|
574
|
+
country: country of search. Defaults to None.
|
|
575
|
+
postalcode: postalcode of search. Defaults to None.
|
|
576
|
+
latitude: geographic coordinate (north-south position). Defaults to None.
|
|
577
|
+
longitude: geographic coordinate (east-west position); if latitude and
|
|
578
|
+
longitude are set, the other parameters are not used. Defaults to None.
|
|
579
|
+
radius: expand the search square by the distance in kilometers. Defaults to 0.
|
|
580
|
+
max_results: max number of results. If None, returns results only from the first response. Defaults to None.
|
|
581
|
+
|
|
582
|
+
Returns:
|
|
583
|
+
List of dictionaries with maps search results, or None if there was an error.
|
|
584
|
+
|
|
585
|
+
Raises:
|
|
586
|
+
WebscoutE: Base exception for webscout errors.
|
|
587
|
+
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
588
|
+
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
589
|
+
"""
|
|
590
|
+
result = await self._loop.run_in_executor(
|
|
591
|
+
self._executor,
|
|
592
|
+
super().maps,
|
|
593
|
+
keywords,
|
|
594
|
+
place,
|
|
595
|
+
street,
|
|
596
|
+
city,
|
|
597
|
+
county,
|
|
598
|
+
state,
|
|
599
|
+
country,
|
|
600
|
+
postalcode,
|
|
601
|
+
latitude,
|
|
602
|
+
longitude,
|
|
603
|
+
radius,
|
|
604
|
+
max_results,
|
|
605
|
+
)
|
|
606
|
+
return result
|
|
607
|
+
|
|
608
|
+
async def atranslate(
|
|
609
|
+
self,
|
|
610
|
+
keywords: Union[List[str], str],
|
|
611
|
+
from_: Optional[str] = None,
|
|
612
|
+
to: str = "en",
|
|
613
|
+
) -> List[Dict[str, str]]:
|
|
614
|
+
"""webscout async translate.
|
|
615
|
+
|
|
616
|
+
Args:
|
|
617
|
+
keywords: string or list of strings to translate.
|
|
618
|
+
from_: translate from (defaults automatically). Defaults to None.
|
|
619
|
+
to: what language to translate. Defaults to "en".
|
|
620
|
+
|
|
621
|
+
Returns:
|
|
622
|
+
List od dictionaries with translated keywords.
|
|
623
|
+
|
|
624
|
+
Raises:
|
|
625
|
+
WebscoutE: Base exception for webscout errors.
|
|
626
|
+
RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
|
|
627
|
+
TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
|
|
628
|
+
"""
|
|
629
|
+
result = await self._loop.run_in_executor(
|
|
630
|
+
self._executor,
|
|
631
|
+
super().translate,
|
|
632
|
+
keywords,
|
|
633
|
+
from_,
|
|
634
|
+
to,
|
|
635
|
+
)
|
|
636
636
|
return result
|