bing.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """This is the implementation of the Bing-WEB engine. Some of this
  4. implementations are shared by other engines:
  5. - :ref:`bing images engine`
  6. - :ref:`bing news engine`
  7. - :ref:`bing videos engine`
  8. On the `preference page`_ Bing offers a lot of languages an regions (see section
  9. LANGUAGE and COUNTRY/REGION). The Language is the language of the UI, we need
  10. in SearXNG to get the translations of data such as *"published last week"*.
  11. There is a description of the offical search-APIs_, unfortunately this is not
  12. the API we can use or that bing itself would use. You can look up some things
  13. in the API to get a better picture of bing, but the value specifications like
  14. the market codes are usually outdated or at least no longer used by bing itself.
  15. The market codes have been harmonized and are identical for web, video and
  16. images. The news area has also been harmonized with the other categories. Only
  17. political adjustments still seem to be made -- for example, there is no news
  18. category for the Chinese market.
  19. .. _preference page: https://www.bing.com/account/general
  20. .. _search-APIs: https://learn.microsoft.com/en-us/bing/search-apis/
  21. """
  22. # pylint: disable=too-many-branches, invalid-name
  23. from typing import TYPE_CHECKING
  24. import base64
  25. import re
  26. import time
  27. from urllib.parse import parse_qs, urlencode, urlparse
  28. from lxml import html
  29. import babel
  30. import babel.languages
  31. from searx.utils import eval_xpath, extract_text, eval_xpath_list, eval_xpath_getindex
  32. from searx.locales import language_tag, region_tag
  33. from searx.enginelib.traits import EngineTraits
  34. if TYPE_CHECKING:
  35. import logging
  36. logger = logging.getLogger()
  37. traits: EngineTraits
  38. about = {
  39. "website": 'https://www.bing.com',
  40. "wikidata_id": 'Q182496',
  41. "official_api_documentation": 'https://www.microsoft.com/en-us/bing/apis/bing-web-search-api',
  42. "use_official_api": False,
  43. "require_api_key": False,
  44. "results": 'HTML',
  45. }
  46. # engine dependent config
  47. categories = ['general', 'web']
  48. paging = True
  49. time_range_support = True
  50. safesearch = True
  51. """Bing results are always SFW. To get NSFW links from bing some age
  52. verification by a cookie is needed / thats not possible in SearXNG.
  53. """
  54. base_url = 'https://www.bing.com/search'
  55. """Bing (Web) search URL"""
  56. def _page_offset(pageno):
  57. return (int(pageno) - 1) * 10 + 1
  58. def set_bing_cookies(params, engine_language, engine_region):
  59. params['cookies']['_EDGE_CD'] = f'm={engine_region}&u={engine_language}'
  60. params['cookies']['_EDGE_S'] = f'mkt={engine_region}&ui={engine_language}'
  61. logger.debug("bing cookies: %s", params['cookies'])
  62. def request(query, params):
  63. """Assemble a Bing-Web request."""
  64. engine_region = traits.get_region(params['searxng_locale'], traits.all_locale) # type: ignore
  65. engine_language = traits.get_language(params['searxng_locale'], 'en') # type: ignore
  66. set_bing_cookies(params, engine_language, engine_region)
  67. page = params.get('pageno', 1)
  68. query_params = {
  69. 'q': query,
  70. # if arg 'pq' is missed, somtimes on page 4 we get results from page 1,
  71. # don't ask why it is only sometimes / its M$ and they have never been
  72. # deterministic ;)
  73. 'pq': query,
  74. }
  75. # To get correct page, arg first and this arg FORM is needed, the value PERE
  76. # is on page 2, on page 3 its PERE1 and on page 4 its PERE2 .. and so forth.
  77. # The 'first' arg should never send on page 1.
  78. if page > 1:
  79. query_params['first'] = _page_offset(page) # see also arg FORM
  80. if page == 2:
  81. query_params['FORM'] = 'PERE'
  82. elif page > 2:
  83. query_params['FORM'] = 'PERE%s' % (page - 2)
  84. params['url'] = f'{base_url}?{urlencode(query_params)}'
  85. if params.get('time_range'):
  86. unix_day = int(time.time() / 86400)
  87. time_ranges = {'day': '1', 'week': '2', 'month': '3', 'year': f'5_{unix_day-365}_{unix_day}'}
  88. params['url'] += f'&filters=ex1:"ez{time_ranges[params["time_range"]]}"'
  89. return params
  90. def response(resp):
  91. # pylint: disable=too-many-locals
  92. results = []
  93. result_len = 0
  94. dom = html.fromstring(resp.text)
  95. # parse results again if nothing is found yet
  96. for result in eval_xpath_list(dom, '//ol[@id="b_results"]/li[contains(@class, "b_algo")]'):
  97. link = eval_xpath_getindex(result, './/h2/a', 0, None)
  98. if link is None:
  99. continue
  100. url = link.attrib.get('href')
  101. title = extract_text(link)
  102. content = eval_xpath(result, './/p')
  103. for p in content:
  104. # Make sure that the element is free of:
  105. # <span class="algoSlug_icon" # data-priority="2">Web</span>
  106. for e in p.xpath('.//span[@class="algoSlug_icon"]'):
  107. e.getparent().remove(e)
  108. content = extract_text(content)
  109. # get the real URL
  110. if url.startswith('https://www.bing.com/ck/a?'):
  111. # get the first value of u parameter
  112. url_query = urlparse(url).query
  113. parsed_url_query = parse_qs(url_query)
  114. param_u = parsed_url_query["u"][0]
  115. # remove "a1" in front
  116. encoded_url = param_u[2:]
  117. # add padding
  118. encoded_url = encoded_url + '=' * (-len(encoded_url) % 4)
  119. # decode base64 encoded URL
  120. url = base64.urlsafe_b64decode(encoded_url).decode()
  121. # append result
  122. results.append({'url': url, 'title': title, 'content': content})
  123. # get number_of_results
  124. try:
  125. result_len_container = "".join(eval_xpath(dom, '//span[@class="sb_count"]//text()'))
  126. if "-" in result_len_container:
  127. # Remove the part "from-to" for paginated request ...
  128. result_len_container = result_len_container[result_len_container.find("-") * 2 + 2 :]
  129. result_len_container = re.sub('[^0-9]', '', result_len_container)
  130. if len(result_len_container) > 0:
  131. result_len = int(result_len_container)
  132. except Exception as e: # pylint: disable=broad-except
  133. logger.debug('result error :\n%s', e)
  134. if result_len and _page_offset(resp.search_params.get("pageno", 0)) > result_len:
  135. # Avoid reading more results than avalaible.
  136. # For example, if there is 100 results from some search and we try to get results from 120 to 130,
  137. # Bing will send back the results from 0 to 10 and no error.
  138. # If we compare results count with the first parameter of the request we can avoid this "invalid" results.
  139. return []
  140. results.append({'number_of_results': result_len})
  141. return results
  142. def fetch_traits(engine_traits: EngineTraits):
  143. """Fetch languages and regions from Bing-Web."""
  144. # pylint: disable=import-outside-toplevel
  145. from searx.network import get # see https://github.com/searxng/searxng/issues/762
  146. resp = get("https://www.bing.com/account/general")
  147. if not resp.ok: # type: ignore
  148. print("ERROR: response from bing is not OK.")
  149. dom = html.fromstring(resp.text) # type: ignore
  150. # languages
  151. engine_traits.languages['zh'] = 'zh-hans'
  152. map_lang = {'prs': 'fa-AF', 'en': 'en-us'}
  153. bing_ui_lang_map = {
  154. # HINT: this list probably needs to be supplemented
  155. 'en': 'us', # en --> en-us
  156. 'da': 'dk', # da --> da-dk
  157. }
  158. for href in eval_xpath(dom, '//div[@id="language-section"]//li/a/@href'):
  159. eng_lang = parse_qs(urlparse(href).query)['setlang'][0]
  160. babel_lang = map_lang.get(eng_lang, eng_lang)
  161. try:
  162. sxng_tag = language_tag(babel.Locale.parse(babel_lang.replace('-', '_')))
  163. except babel.UnknownLocaleError:
  164. print("ERROR: language (%s) is unknown by babel" % (babel_lang))
  165. continue
  166. # Language (e.g. 'en' or 'de') from https://www.bing.com/account/general
  167. # is converted by bing to 'en-us' or 'de-de'. But only if there is not
  168. # already a '-' delemitter in the language. For instance 'pt-PT' -->
  169. # 'pt-pt' and 'pt-br' --> 'pt-br'
  170. bing_ui_lang = eng_lang.lower()
  171. if '-' not in bing_ui_lang:
  172. bing_ui_lang = bing_ui_lang + '-' + bing_ui_lang_map.get(bing_ui_lang, bing_ui_lang)
  173. conflict = engine_traits.languages.get(sxng_tag)
  174. if conflict:
  175. if conflict != bing_ui_lang:
  176. print(f"CONFLICT: babel {sxng_tag} --> {conflict}, {bing_ui_lang}")
  177. continue
  178. engine_traits.languages[sxng_tag] = bing_ui_lang
  179. # regions (aka "market codes")
  180. engine_traits.regions['zh-CN'] = 'zh-cn'
  181. map_market_codes = {
  182. 'zh-hk': 'en-hk', # not sure why, but at M$ this is the market code for Hongkong
  183. }
  184. for href in eval_xpath(dom, '//div[@id="region-section"]//li/a/@href'):
  185. cc_tag = parse_qs(urlparse(href).query)['cc'][0]
  186. if cc_tag == 'clear':
  187. engine_traits.all_locale = cc_tag
  188. continue
  189. # add market codes from official languages of the country ..
  190. for lang_tag in babel.languages.get_official_languages(cc_tag, de_facto=True):
  191. if lang_tag not in engine_traits.languages.keys():
  192. # print("ignore lang: %s <-- %s" % (cc_tag, lang_tag))
  193. continue
  194. lang_tag = lang_tag.split('_')[0] # zh_Hant --> zh
  195. market_code = f"{lang_tag}-{cc_tag}" # zh-tw
  196. market_code = map_market_codes.get(market_code, market_code)
  197. sxng_tag = region_tag(babel.Locale.parse('%s_%s' % (lang_tag, cc_tag.upper())))
  198. conflict = engine_traits.regions.get(sxng_tag)
  199. if conflict:
  200. if conflict != market_code:
  201. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, market_code))
  202. continue
  203. engine_traits.regions[sxng_tag] = market_code