startpage.py 8.5 KB

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