startpage.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Startpage (Web)
  4. """
  5. from lxml import html
  6. from dateutil import parser
  7. from datetime import datetime, timedelta
  8. import re
  9. from unicodedata import normalize, combining
  10. from babel import Locale
  11. from babel.localedata import locale_identifiers
  12. from searx.utils import extract_text, eval_xpath, match_language
  13. # about
  14. about = {
  15. "website": 'https://startpage.com',
  16. "wikidata_id": 'Q2333295',
  17. "official_api_documentation": None,
  18. "use_official_api": False,
  19. "require_api_key": False,
  20. "results": 'HTML',
  21. }
  22. # engine dependent config
  23. categories = ['general']
  24. # there is a mechanism to block "bot" search
  25. # (probably the parameter qid), require
  26. # storing of qid's between mulitble search-calls
  27. paging = True
  28. supported_languages_url = 'https://www.startpage.com/do/settings'
  29. # search-url
  30. base_url = 'https://startpage.com/'
  31. search_url = base_url + 'do/search'
  32. # specific xpath variables
  33. # ads xpath //div[@id="results"]/div[@id="sponsored"]//div[@class="result"]
  34. # not ads: div[@class="result"] are the direct childs of div[@id="results"]
  35. results_xpath = '//div[@class="w-gl__result__main"]'
  36. link_xpath = './/a[@class="w-gl__result-title result-link"]'
  37. content_xpath = './/p[@class="w-gl__description"]'
  38. # do search-request
  39. def request(query, params):
  40. params['url'] = search_url
  41. params['method'] = 'POST'
  42. params['data'] = {
  43. 'query': query,
  44. 'page': params['pageno'],
  45. 'cat': 'web',
  46. 'cmd': 'process_search',
  47. 'engine0': 'v1all',
  48. }
  49. # set language if specified
  50. if params['language'] != 'all':
  51. lang_code = match_language(params['language'], supported_languages, fallback=None)
  52. if lang_code:
  53. language_name = supported_languages[lang_code]['alias']
  54. params['data']['language'] = language_name
  55. params['data']['lui'] = language_name
  56. return params
  57. # get response from search-request
  58. def response(resp):
  59. results = []
  60. dom = html.fromstring(resp.text)
  61. # parse results
  62. for result in eval_xpath(dom, results_xpath):
  63. links = eval_xpath(result, link_xpath)
  64. if not links:
  65. continue
  66. link = links[0]
  67. url = link.attrib.get('href')
  68. # block google-ad url's
  69. if re.match(r"^http(s|)://(www\.)?google\.[a-z]+/aclk.*$", url):
  70. continue
  71. # block startpage search url's
  72. if re.match(r"^http(s|)://(www\.)?startpage\.com/do/search\?.*$", url):
  73. continue
  74. title = extract_text(link)
  75. if eval_xpath(result, content_xpath):
  76. content = extract_text(eval_xpath(result, content_xpath))
  77. else:
  78. content = ''
  79. published_date = None
  80. # check if search result starts with something like: "2 Sep 2014 ... "
  81. if re.match(r"^([1-9]|[1-2][0-9]|3[0-1]) [A-Z][a-z]{2} [0-9]{4} \.\.\. ", content):
  82. date_pos = content.find('...') + 4
  83. date_string = content[0:date_pos - 5]
  84. # fix content string
  85. content = content[date_pos:]
  86. try:
  87. published_date = parser.parse(date_string, dayfirst=True)
  88. except ValueError:
  89. pass
  90. # check if search result starts with something like: "5 days ago ... "
  91. elif re.match(r"^[0-9]+ days? ago \.\.\. ", content):
  92. date_pos = content.find('...') + 4
  93. date_string = content[0:date_pos - 5]
  94. # calculate datetime
  95. published_date = datetime.now() - timedelta(days=int(re.match(r'\d+', date_string).group()))
  96. # fix content string
  97. content = content[date_pos:]
  98. if published_date:
  99. # append result
  100. results.append({'url': url,
  101. 'title': title,
  102. 'content': content,
  103. 'publishedDate': published_date})
  104. else:
  105. # append result
  106. results.append({'url': url,
  107. 'title': title,
  108. 'content': content})
  109. # return results
  110. return results
  111. # get supported languages from their site
  112. def _fetch_supported_languages(resp):
  113. # startpage's language selector is a mess
  114. # each option has a displayed name and a value, either of which may represent the language name
  115. # in the native script, the language name in English, an English transliteration of the native name,
  116. # the English name of the writing script used by the language, or occasionally something else entirely.
  117. # this cases are so special they need to be hardcoded, a couple of them are mispellings
  118. language_names = {
  119. 'english_uk': 'en-GB',
  120. 'fantizhengwen': ['zh-TW', 'zh-HK'],
  121. 'hangul': 'ko',
  122. 'malayam': 'ml',
  123. 'norsk': 'nb',
  124. 'sinhalese': 'si',
  125. 'sudanese': 'su'
  126. }
  127. # get the English name of every language known by babel
  128. language_names.update({name.lower(): lang_code for lang_code, name in Locale('en')._data['languages'].items()})
  129. # get the native name of every language known by babel
  130. for lang_code in filter(lambda lang_code: lang_code.find('_') == -1, locale_identifiers()):
  131. native_name = Locale(lang_code).get_language_name().lower()
  132. # add native name exactly as it is
  133. language_names[native_name] = lang_code
  134. # add "normalized" language name (i.e. français becomes francais and español becomes espanol)
  135. unaccented_name = ''.join(filter(lambda c: not combining(c), normalize('NFKD', native_name)))
  136. if len(unaccented_name) == len(unaccented_name.encode()):
  137. # add only if result is ascii (otherwise "normalization" didn't work)
  138. language_names[unaccented_name] = lang_code
  139. dom = html.fromstring(resp.text)
  140. sp_lang_names = []
  141. for option in dom.xpath('//form[@id="settings-form"]//select[@name="language"]/option'):
  142. sp_lang_names.append((option.get('value'), extract_text(option).lower()))
  143. supported_languages = {}
  144. for sp_option_value, sp_option_text in sp_lang_names:
  145. lang_code = language_names.get(sp_option_value) or language_names.get(sp_option_text)
  146. if isinstance(lang_code, str):
  147. supported_languages[lang_code] = {'alias': sp_option_value}
  148. elif isinstance(lang_code, list):
  149. for lc in lang_code:
  150. supported_languages[lc] = {'alias': sp_option_value}
  151. else:
  152. print('Unknown language option in Startpage: {} ({})'.format(sp_option_value, sp_option_text))
  153. return supported_languages