bing.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. max_page = 200
  50. """200 pages maximum (``&first=1991``)"""
  51. time_range_support = True
  52. safesearch = True
  53. """Bing results are always SFW. To get NSFW links from bing some age
  54. verification by a cookie is needed / thats not possible in SearXNG.
  55. """
  56. base_url = 'https://www.bing.com/search'
  57. """Bing (Web) search URL"""
  58. def _page_offset(pageno):
  59. return (int(pageno) - 1) * 10 + 1
  60. def set_bing_cookies(params, engine_language, engine_region):
  61. params['cookies']['_EDGE_CD'] = f'm={engine_region}&u={engine_language}'
  62. params['cookies']['_EDGE_S'] = f'mkt={engine_region}&ui={engine_language}'
  63. logger.debug("bing cookies: %s", params['cookies'])
  64. def request(query, params):
  65. """Assemble a Bing-Web request."""
  66. engine_region = traits.get_region(params['searxng_locale'], traits.all_locale) # type: ignore
  67. engine_language = traits.get_language(params['searxng_locale'], 'en') # type: ignore
  68. set_bing_cookies(params, engine_language, engine_region)
  69. page = params.get('pageno', 1)
  70. query_params = {
  71. 'q': query,
  72. # if arg 'pq' is missed, somtimes on page 4 we get results from page 1,
  73. # don't ask why it is only sometimes / its M$ and they have never been
  74. # deterministic ;)
  75. 'pq': query,
  76. }
  77. # To get correct page, arg first and this arg FORM is needed, the value PERE
  78. # is on page 2, on page 3 its PERE1 and on page 4 its PERE2 .. and so forth.
  79. # The 'first' arg should never send on page 1.
  80. if page > 1:
  81. query_params['first'] = _page_offset(page) # see also arg FORM
  82. if page == 2:
  83. query_params['FORM'] = 'PERE'
  84. elif page > 2:
  85. query_params['FORM'] = 'PERE%s' % (page - 2)
  86. params['url'] = f'{base_url}?{urlencode(query_params)}'
  87. if params.get('time_range'):
  88. unix_day = int(time.time() / 86400)
  89. time_ranges = {'day': '1', 'week': '2', 'month': '3', 'year': f'5_{unix_day-365}_{unix_day}'}
  90. params['url'] += f'&filters=ex1:"ez{time_ranges[params["time_range"]]}"'
  91. return params
  92. def response(resp):
  93. # pylint: disable=too-many-locals
  94. results = []
  95. result_len = 0
  96. dom = html.fromstring(resp.text)
  97. # parse results again if nothing is found yet
  98. for result in eval_xpath_list(dom, '//ol[@id="b_results"]/li[contains(@class, "b_algo")]'):
  99. link = eval_xpath_getindex(result, './/h2/a', 0, None)
  100. if link is None:
  101. continue
  102. url = link.attrib.get('href')
  103. title = extract_text(link)
  104. content = eval_xpath(result, './/p')
  105. for p in content:
  106. # Make sure that the element is free of:
  107. # <span class="algoSlug_icon" # data-priority="2">Web</span>
  108. for e in p.xpath('.//span[@class="algoSlug_icon"]'):
  109. e.getparent().remove(e)
  110. content = extract_text(content)
  111. # get the real URL
  112. if url.startswith('https://www.bing.com/ck/a?'):
  113. # get the first value of u parameter
  114. url_query = urlparse(url).query
  115. parsed_url_query = parse_qs(url_query)
  116. param_u = parsed_url_query["u"][0]
  117. # remove "a1" in front
  118. encoded_url = param_u[2:]
  119. # add padding
  120. encoded_url = encoded_url + '=' * (-len(encoded_url) % 4)
  121. # decode base64 encoded URL
  122. url = base64.urlsafe_b64decode(encoded_url).decode()
  123. # append result
  124. results.append({'url': url, 'title': title, 'content': content})
  125. # get number_of_results
  126. try:
  127. result_len_container = "".join(eval_xpath(dom, '//span[@class="sb_count"]//text()'))
  128. if "-" in result_len_container:
  129. # Remove the part "from-to" for paginated request ...
  130. result_len_container = result_len_container[result_len_container.find("-") * 2 + 2 :]
  131. result_len_container = re.sub('[^0-9]', '', result_len_container)
  132. if len(result_len_container) > 0:
  133. result_len = int(result_len_container)
  134. except Exception as e: # pylint: disable=broad-except
  135. logger.debug('result error :\n%s', e)
  136. if result_len and _page_offset(resp.search_params.get("pageno", 0)) > result_len:
  137. # Avoid reading more results than avalaible.
  138. # For example, if there is 100 results from some search and we try to get results from 120 to 130,
  139. # Bing will send back the results from 0 to 10 and no error.
  140. # If we compare results count with the first parameter of the request we can avoid this "invalid" results.
  141. return []
  142. results.append({'number_of_results': result_len})
  143. return results
  144. def fetch_traits(engine_traits: EngineTraits):
  145. """Fetch languages and regions from Bing-Web."""
  146. # pylint: disable=import-outside-toplevel
  147. from searx.network import get # see https://github.com/searxng/searxng/issues/762
  148. resp = get("https://www.bing.com/account/general")
  149. if not resp.ok: # type: ignore
  150. print("ERROR: response from bing is not OK.")
  151. dom = html.fromstring(resp.text) # type: ignore
  152. # languages
  153. engine_traits.languages['zh'] = 'zh-hans'
  154. map_lang = {'prs': 'fa-AF', 'en': 'en-us'}
  155. bing_ui_lang_map = {
  156. # HINT: this list probably needs to be supplemented
  157. 'en': 'us', # en --> en-us
  158. 'da': 'dk', # da --> da-dk
  159. }
  160. for href in eval_xpath(dom, '//div[@id="language-section"]//li/a/@href'):
  161. eng_lang = parse_qs(urlparse(href).query)['setlang'][0]
  162. babel_lang = map_lang.get(eng_lang, eng_lang)
  163. try:
  164. sxng_tag = language_tag(babel.Locale.parse(babel_lang.replace('-', '_')))
  165. except babel.UnknownLocaleError:
  166. print("ERROR: language (%s) is unknown by babel" % (babel_lang))
  167. continue
  168. # Language (e.g. 'en' or 'de') from https://www.bing.com/account/general
  169. # is converted by bing to 'en-us' or 'de-de'. But only if there is not
  170. # already a '-' delemitter in the language. For instance 'pt-PT' -->
  171. # 'pt-pt' and 'pt-br' --> 'pt-br'
  172. bing_ui_lang = eng_lang.lower()
  173. if '-' not in bing_ui_lang:
  174. bing_ui_lang = bing_ui_lang + '-' + bing_ui_lang_map.get(bing_ui_lang, bing_ui_lang)
  175. conflict = engine_traits.languages.get(sxng_tag)
  176. if conflict:
  177. if conflict != bing_ui_lang:
  178. print(f"CONFLICT: babel {sxng_tag} --> {conflict}, {bing_ui_lang}")
  179. continue
  180. engine_traits.languages[sxng_tag] = bing_ui_lang
  181. # regions (aka "market codes")
  182. engine_traits.regions['zh-CN'] = 'zh-cn'
  183. map_market_codes = {
  184. 'zh-hk': 'en-hk', # not sure why, but at M$ this is the market code for Hongkong
  185. }
  186. for href in eval_xpath(dom, '//div[@id="region-section"]//li/a/@href'):
  187. cc_tag = parse_qs(urlparse(href).query)['cc'][0]
  188. if cc_tag == 'clear':
  189. engine_traits.all_locale = cc_tag
  190. continue
  191. # add market codes from official languages of the country ..
  192. for lang_tag in babel.languages.get_official_languages(cc_tag, de_facto=True):
  193. if lang_tag not in engine_traits.languages.keys():
  194. # print("ignore lang: %s <-- %s" % (cc_tag, lang_tag))
  195. continue
  196. lang_tag = lang_tag.split('_')[0] # zh_Hant --> zh
  197. market_code = f"{lang_tag}-{cc_tag}" # zh-tw
  198. market_code = map_market_codes.get(market_code, market_code)
  199. sxng_tag = region_tag(babel.Locale.parse('%s_%s' % (lang_tag, cc_tag.upper())))
  200. conflict = engine_traits.regions.get(sxng_tag)
  201. if conflict:
  202. if conflict != market_code:
  203. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, market_code))
  204. continue
  205. engine_traits.regions[sxng_tag] = market_code