94from searx.utils import extr, extract_text, eval_xpath, gen_useragent, html_to_text, humanize_bytes, remove_pua_from_str
181 """Get an actual ``sc`` argument from Startpage's search form (HTML page).
183 Startpage puts a ``sc`` argument on every HTML :py:obj:`search form
184 <search_form_xpath>`. Without this argument Startpage considers the request
185 is from a bot. We do not know what is encoded in the value of the ``sc``
186 argument, but it seems to be a kind of a *timestamp*.
188 Startpage's search form generates a new sc-code on each request. This
189 function scrapes a new sc-code from Startpage's home page every
190 :py:obj:`sc_code_cache_sec` seconds."""
192 sc_code = CACHE.get(
"SC_CODE")
195 logger.debug(
"get_sc_code: using cached value: %s", sc_code)
198 headers = {**params[
'headers']}
201 if searxng_locale ==
'all':
202 searxng_locale =
'en-US'
203 locale = babel.Locale.parse(searxng_locale, sep=
'-')
205 if send_accept_language_header:
206 ac_lang = locale.language
208 ac_lang =
"%s-%s,%s;q=0.9,*;q=0.5" % (
213 headers[
'Accept-Language'] = ac_lang
215 get_sc_url = base_url +
'/'
216 logger.debug(
"get_sc_code: querying new sc timestamp @ %s", get_sc_url)
217 logger.debug(
"get_sc_code: request headers: %s", headers)
218 resp = get(get_sc_url, headers=headers)
224 if str(resp.url).startswith(
'https://www.startpage.com/sp/captcha'):
226 message=
"get_sc_code: got redirected to https://www.startpage.com/sp/captcha",
229 dom = lxml.html.fromstring(resp.text)
232 sc_code = eval_xpath(dom, search_form_xpath +
'//input[@name="sc"]/@value')[0]
233 except IndexError
as exc:
234 logger.debug(
"suspend startpage API --> https://github.com/searxng/searxng/pull/695")
236 message=
"get_sc_code: [PR-695] querying new sc timestamp failed! (%s)" % resp.url,
239 sc_code = str(sc_code)
240 logger.debug(
"get_sc_code: new value is: %s", sc_code)
241 CACHE.set(key=
"SC_CODE", value=sc_code, expire=sc_code_cache_sec)
318 published_date =
None
321 if re.match(
r"^([1-9]|[1-2][0-9]|3[0-1]) [A-Z][a-z]{2} [0-9]{4} \.\.\. ", content):
322 date_pos = content.find(
'...') + 4
323 date_string = content[0 : date_pos - 5]
325 content = content[date_pos:]
328 published_date = dateutil.parser.parse(date_string, dayfirst=
True)
333 elif re.match(
r"^[0-9]+ days? ago \.\.\. ", content):
334 date_pos = content.find(
'...') + 4
335 date_string = content[0 : date_pos - 5]
338 published_date = datetime.now() - timedelta(days=int(re.match(
r'\d+', date_string).group()))
341 content = content[date_pos:]
343 return content, published_date
381 url = result.get(
'altClickUrl')
386 if result.get(
'thumbnailUrl'):
387 thumbnailUrl = base_url + result[
'thumbnailUrl']
390 if result.get(
'width')
and result.get(
'height'):
391 resolution = f
"{result['width']}x{result['height']}"
394 if result.get(
'filesize'):
395 size_str =
''.join(filter(str.isdigit, result[
'filesize']))
396 filesize = humanize_bytes(int(size_str))
399 'template':
'images.html',
401 'title': html_to_text(result[
'title']),
403 'img_src': result.get(
'rawImageUrl'),
404 'thumbnail_src': thumbnailUrl,
405 'resolution': resolution,
406 'img_format': result.get(
'format'),
407 'filesize': filesize,
433 """Fetch :ref:`languages <startpage languages>` and :ref:`regions <startpage
434 regions>` from Startpage."""
438 'User-Agent': gen_useragent(),
439 'Accept-Language':
"en-US,en;q=0.5",
441 resp = get(
'https://www.startpage.com/do/settings', headers=headers)
444 print(
"ERROR: response from Startpage is not OK.")
446 dom = lxml.html.fromstring(resp.text)
451 for option
in dom.xpath(
'//form[@name="settings"]//select[@name="search_results_region"]/option'):
452 sp_region_names.append(option.get(
'value'))
454 for eng_tag
in sp_region_names:
457 babel_region_tag = {
'no_NO':
'nb_NO'}.get(eng_tag, eng_tag)
459 if '-' in babel_region_tag:
460 l, r = babel_region_tag.split(
'-')
462 sxng_tag = region_tag(babel.Locale.parse(l +
'_' + r, sep=
'_'))
466 sxng_tag = region_tag(babel.Locale.parse(babel_region_tag, sep=
'_'))
468 except babel.UnknownLocaleError:
469 print(
"ERROR: can't determine babel locale of startpage's locale %s" % eng_tag)
472 conflict = engine_traits.regions.get(sxng_tag)
474 if conflict != eng_tag:
475 print(
"CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
477 engine_traits.regions[sxng_tag] = eng_tag
481 catalog_engine2code = {name.lower(): lang_code
for lang_code, name
in babel.Locale(
'en').languages.items()}
485 for lang_code
in filter(
lambda lang_code: lang_code.find(
'_') == -1, babel.localedata.locale_identifiers()):
486 native_name = babel.Locale(lang_code).get_language_name()
488 print(f
"ERROR: language name of startpage's language {lang_code} is unknown by babel")
490 native_name = native_name.lower()
492 catalog_engine2code[native_name] = lang_code
495 unaccented_name =
''.join(filter(
lambda c:
not combining(c), normalize(
'NFKD', native_name)))
496 if len(unaccented_name) == len(unaccented_name.encode()):
498 catalog_engine2code[unaccented_name] = lang_code
502 catalog_engine2code.update(
505 'fantizhengwen':
'zh_Hant',
519 for option
in dom.xpath(
'//form[@name="settings"]//select[@name="language"]/option'):
521 eng_tag = option.get(
'value')
522 if eng_tag
in skip_eng_tags:
524 name = extract_text(option).lower()
526 sxng_tag = catalog_engine2code.get(eng_tag)
528 sxng_tag = catalog_engine2code[name]
530 conflict = engine_traits.languages.get(sxng_tag)
532 if conflict != eng_tag:
533 print(
"CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
535 engine_traits.languages[sxng_tag] = eng_tag
get_sc_code(searxng_locale, params)
dict[str, Any]|None _get_image_result(result)
fetch_traits(EngineTraits engine_traits)
tuple[str, datetime|None] _parse_published_date(str content)