startpage.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Startpage (Web)
  4. """
  5. import re
  6. from time import time
  7. from urllib.parse import urlencode
  8. from unicodedata import normalize, combining
  9. from datetime import datetime, timedelta
  10. from dateutil import parser
  11. from lxml import html
  12. from babel import Locale
  13. from babel.localedata import locale_identifiers
  14. from searx.network import get
  15. from searx.utils import extract_text, eval_xpath, match_language
  16. from searx.exceptions import (
  17. SearxEngineResponseException,
  18. SearxEngineCaptchaException,
  19. )
  20. # about
  21. about = {
  22. "website": 'https://startpage.com',
  23. "wikidata_id": 'Q2333295',
  24. "official_api_documentation": None,
  25. "use_official_api": False,
  26. "require_api_key": False,
  27. "results": 'HTML',
  28. }
  29. # engine dependent config
  30. categories = ['general', 'web']
  31. # there is a mechanism to block "bot" search
  32. # (probably the parameter qid), require
  33. # storing of qid's between mulitble search-calls
  34. paging = True
  35. supported_languages_url = 'https://www.startpage.com/do/settings'
  36. # search-url
  37. base_url = 'https://startpage.com/'
  38. search_url = base_url + 'sp/search?'
  39. # specific xpath variables
  40. # ads xpath //div[@id="results"]/div[@id="sponsored"]//div[@class="result"]
  41. # not ads: div[@class="result"] are the direct childs of div[@id="results"]
  42. results_xpath = '//div[@class="w-gl__result__main"]'
  43. link_xpath = './/a[@class="w-gl__result-title result-link"]'
  44. content_xpath = './/p[@class="w-gl__description"]'
  45. # timestamp of the last fetch of 'sc' code
  46. sc_code_ts = 0
  47. sc_code = ''
  48. def raise_captcha(resp):
  49. if str(resp.url).startswith('https://www.startpage.com/sp/captcha'):
  50. # suspend CAPTCHA for 7 days
  51. raise SearxEngineCaptchaException(suspended_time=7 * 24 * 3600)
  52. def get_sc_code(headers):
  53. """Get an actual `sc` argument from startpage's home page.
  54. Startpage puts a `sc` argument on every link. Without this argument
  55. startpage considers the request is from a bot. We do not know what is
  56. encoded in the value of the `sc` argument, but it seems to be a kind of a
  57. *time-stamp*. This *time-stamp* is valid for a few hours.
  58. This function scrap a new *time-stamp* from startpage's home page every hour
  59. (3000 sec).
  60. """
  61. global sc_code_ts, sc_code # pylint: disable=global-statement
  62. if time() > (sc_code_ts + 3000):
  63. logger.debug("query new sc time-stamp ...")
  64. resp = get(base_url, headers=headers)
  65. raise_captcha(resp)
  66. dom = html.fromstring(resp.text)
  67. try:
  68. # href --> '/?sc=adrKJMgF8xwp20'
  69. href = eval_xpath(dom, '//a[@class="footer-home__logo"]')[0].get('href')
  70. except IndexError as exc:
  71. # suspend startpage API --> https://github.com/searxng/searxng/pull/695
  72. raise SearxEngineResponseException(
  73. suspended_time=7 * 24 * 3600, message="PR-695: query new sc time-stamp failed!"
  74. ) from exc
  75. sc_code = href[5:]
  76. sc_code_ts = time()
  77. logger.debug("new value is: %s", sc_code)
  78. return sc_code
  79. # do search-request
  80. def request(query, params):
  81. # pylint: disable=line-too-long
  82. # The format string from Startpage's FFox add-on [1]::
  83. #
  84. # https://www.startpage.com/do/dsearch?query={searchTerms}&cat=web&pl=ext-ff&language=__MSG_extensionUrlLanguage__&extVersion=1.3.0
  85. #
  86. # [1] https://addons.mozilla.org/en-US/firefox/addon/startpage-private-search/
  87. args = {
  88. 'query': query,
  89. 'page': params['pageno'],
  90. 'cat': 'web',
  91. # 'pl': 'ext-ff',
  92. # 'extVersion': '1.3.0',
  93. # 'abp': "-1",
  94. 'sc': get_sc_code(params['headers']),
  95. }
  96. # set language if specified
  97. if params['language'] != 'all':
  98. lang_code = match_language(params['language'], supported_languages, fallback=None)
  99. if lang_code:
  100. language_name = supported_languages[lang_code]['alias']
  101. args['language'] = language_name
  102. args['lui'] = language_name
  103. params['url'] = search_url + urlencode(args)
  104. return params
  105. # get response from search-request
  106. def response(resp):
  107. results = []
  108. dom = html.fromstring(resp.text)
  109. # parse results
  110. for result in eval_xpath(dom, results_xpath):
  111. links = eval_xpath(result, link_xpath)
  112. if not links:
  113. continue
  114. link = links[0]
  115. url = link.attrib.get('href')
  116. # block google-ad url's
  117. if re.match(r"^http(s|)://(www\.)?google\.[a-z]+/aclk.*$", url):
  118. continue
  119. # block startpage search url's
  120. if re.match(r"^http(s|)://(www\.)?startpage\.com/do/search\?.*$", url):
  121. continue
  122. title = extract_text(link)
  123. if eval_xpath(result, content_xpath):
  124. content = extract_text(eval_xpath(result, content_xpath))
  125. else:
  126. content = ''
  127. published_date = None
  128. # check if search result starts with something like: "2 Sep 2014 ... "
  129. if re.match(r"^([1-9]|[1-2][0-9]|3[0-1]) [A-Z][a-z]{2} [0-9]{4} \.\.\. ", content):
  130. date_pos = content.find('...') + 4
  131. date_string = content[0 : date_pos - 5]
  132. # fix content string
  133. content = content[date_pos:]
  134. try:
  135. published_date = parser.parse(date_string, dayfirst=True)
  136. except ValueError:
  137. pass
  138. # check if search result starts with something like: "5 days ago ... "
  139. elif re.match(r"^[0-9]+ days? ago \.\.\. ", content):
  140. date_pos = content.find('...') + 4
  141. date_string = content[0 : date_pos - 5]
  142. # calculate datetime
  143. published_date = datetime.now() - timedelta(days=int(re.match(r'\d+', date_string).group()))
  144. # fix content string
  145. content = content[date_pos:]
  146. if published_date:
  147. # append result
  148. results.append({'url': url, 'title': title, 'content': content, 'publishedDate': published_date})
  149. else:
  150. # append result
  151. results.append({'url': url, 'title': title, 'content': content})
  152. # return results
  153. return results
  154. # get supported languages from their site
  155. def _fetch_supported_languages(resp):
  156. # startpage's language selector is a mess each option has a displayed name
  157. # and a value, either of which may represent the language name in the native
  158. # script, the language name in English, an English transliteration of the
  159. # native name, the English name of the writing script used by the language,
  160. # or occasionally something else entirely.
  161. # this cases are so special they need to be hardcoded, a couple of them are mispellings
  162. language_names = {
  163. 'english_uk': 'en-GB',
  164. 'fantizhengwen': ['zh-TW', 'zh-HK'],
  165. 'hangul': 'ko',
  166. 'malayam': 'ml',
  167. 'norsk': 'nb',
  168. 'sinhalese': 'si',
  169. 'sudanese': 'su',
  170. }
  171. # get the English name of every language known by babel
  172. language_names.update(
  173. {
  174. # fmt: off
  175. name.lower(): lang_code
  176. # pylint: disable=protected-access
  177. for lang_code, name in Locale('en')._data['languages'].items()
  178. # fmt: on
  179. }
  180. )
  181. # get the native name of every language known by babel
  182. for lang_code in filter(lambda lang_code: lang_code.find('_') == -1, locale_identifiers()):
  183. native_name = Locale(lang_code).get_language_name().lower()
  184. # add native name exactly as it is
  185. language_names[native_name] = lang_code
  186. # add "normalized" language name (i.e. français becomes francais and español becomes espanol)
  187. unaccented_name = ''.join(filter(lambda c: not combining(c), normalize('NFKD', native_name)))
  188. if len(unaccented_name) == len(unaccented_name.encode()):
  189. # add only if result is ascii (otherwise "normalization" didn't work)
  190. language_names[unaccented_name] = lang_code
  191. dom = html.fromstring(resp.text)
  192. sp_lang_names = []
  193. for option in dom.xpath('//form[@id="settings-form"]//select[@name="language"]/option'):
  194. sp_lang_names.append((option.get('value'), extract_text(option).lower()))
  195. supported_languages = {}
  196. for sp_option_value, sp_option_text in sp_lang_names:
  197. lang_code = language_names.get(sp_option_value) or language_names.get(sp_option_text)
  198. if isinstance(lang_code, str):
  199. supported_languages[lang_code] = {'alias': sp_option_value}
  200. elif isinstance(lang_code, list):
  201. for _lc in lang_code:
  202. supported_languages[_lc] = {'alias': sp_option_value}
  203. else:
  204. print('Unknown language option in Startpage: {} ({})'.format(sp_option_value, sp_option_text))
  205. return supported_languages