startpage.py 8.6 KB

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