bing.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """This is the implementation of the Bing-WEB engine. Some of this
  3. implementations are shared by other engines:
  4. - :ref:`bing images engine`
  5. - :ref:`bing news engine`
  6. - :ref:`bing videos engine`
  7. On the `preference page`_ Bing offers a lot of languages an regions (see section
  8. LANGUAGE and COUNTRY/REGION). The Language is the language of the UI, we need
  9. in SearXNG to get the translations of data such as *"published last week"*.
  10. There is a description of the official search-APIs_, unfortunately this is not
  11. the API we can use or that bing itself would use. You can look up some things
  12. in the API to get a better picture of bing, but the value specifications like
  13. the market codes are usually outdated or at least no longer used by bing itself.
  14. The market codes have been harmonized and are identical for web, video and
  15. images. The news area has also been harmonized with the other categories. Only
  16. political adjustments still seem to be made -- for example, there is no news
  17. category for the Chinese market.
  18. .. _preference page: https://www.bing.com/account/general
  19. .. _search-APIs: https://learn.microsoft.com/en-us/bing/search-apis/
  20. """
  21. # pylint: disable=too-many-branches, invalid-name
  22. from typing import TYPE_CHECKING
  23. import base64
  24. import re
  25. import time
  26. from urllib.parse import parse_qs, urlencode, urlparse
  27. from lxml import html
  28. import babel
  29. import babel.languages
  30. from searx.utils import eval_xpath, extract_text, eval_xpath_list, eval_xpath_getindex
  31. from searx.locales import language_tag, region_tag
  32. from searx.enginelib.traits import EngineTraits
  33. from searx.exceptions import SearxEngineAPIException
  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, sometimes 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. if results:
  127. result_len_container = "".join(eval_xpath(dom, '//span[@class="sb_count"]//text()'))
  128. if "-" in result_len_container:
  129. start_str, result_len_container = re.split(r'-\d+', result_len_container)
  130. start = int(start_str)
  131. else:
  132. start = 1
  133. result_len_container = re.sub('[^0-9]', '', result_len_container)
  134. if len(result_len_container) > 0:
  135. result_len = int(result_len_container)
  136. expected_start = _page_offset(resp.search_params.get("pageno", 1))
  137. if expected_start != start:
  138. if expected_start > result_len:
  139. # Avoid reading more results than available.
  140. # For example, if there is 100 results from some search and we try to get results from 120 to 130,
  141. # Bing will send back the results from 0 to 10 and no error.
  142. # If we compare results count with the first parameter of the request we can avoid this "invalid"
  143. # results.
  144. return []
  145. # Sometimes Bing will send back the first result page instead of the requested page as a rate limiting
  146. # measure.
  147. msg = f"Expected results to start at {expected_start}, but got results starting at {start}"
  148. raise SearxEngineAPIException(msg)
  149. results.append({'number_of_results': result_len})
  150. return results
  151. def fetch_traits(engine_traits: EngineTraits):
  152. """Fetch languages and regions from Bing-Web."""
  153. # pylint: disable=import-outside-toplevel
  154. from searx.network import get # see https://github.com/searxng/searxng/issues/762
  155. from searx.utils import gen_useragent
  156. headers = {
  157. "User-Agent": gen_useragent(),
  158. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
  159. "Accept-Language": "en-US;q=0.5,en;q=0.3",
  160. "Accept-Encoding": "gzip, deflate, br",
  161. "DNT": "1",
  162. "Connection": "keep-alive",
  163. "Upgrade-Insecure-Requests": "1",
  164. "Sec-GPC": "1",
  165. "Cache-Control": "max-age=0",
  166. }
  167. resp = get("https://www.bing.com/account/general", headers=headers)
  168. if not resp.ok: # type: ignore
  169. print("ERROR: response from bing is not OK.")
  170. dom = html.fromstring(resp.text) # type: ignore
  171. # languages
  172. engine_traits.languages['zh'] = 'zh-hans'
  173. map_lang = {'prs': 'fa-AF', 'en': 'en-us'}
  174. bing_ui_lang_map = {
  175. # HINT: this list probably needs to be supplemented
  176. 'en': 'us', # en --> en-us
  177. 'da': 'dk', # da --> da-dk
  178. }
  179. for href in eval_xpath(dom, '//div[@id="language-section-content"]//div[@class="languageItem"]/a/@href'):
  180. eng_lang = parse_qs(urlparse(href).query)['setlang'][0]
  181. babel_lang = map_lang.get(eng_lang, eng_lang)
  182. try:
  183. sxng_tag = language_tag(babel.Locale.parse(babel_lang.replace('-', '_')))
  184. except babel.UnknownLocaleError:
  185. print("ERROR: language (%s) is unknown by babel" % (babel_lang))
  186. continue
  187. # Language (e.g. 'en' or 'de') from https://www.bing.com/account/general
  188. # is converted by bing to 'en-us' or 'de-de'. But only if there is not
  189. # already a '-' delemitter in the language. For instance 'pt-PT' -->
  190. # 'pt-pt' and 'pt-br' --> 'pt-br'
  191. bing_ui_lang = eng_lang.lower()
  192. if '-' not in bing_ui_lang:
  193. bing_ui_lang = bing_ui_lang + '-' + bing_ui_lang_map.get(bing_ui_lang, bing_ui_lang)
  194. conflict = engine_traits.languages.get(sxng_tag)
  195. if conflict:
  196. if conflict != bing_ui_lang:
  197. print(f"CONFLICT: babel {sxng_tag} --> {conflict}, {bing_ui_lang}")
  198. continue
  199. engine_traits.languages[sxng_tag] = bing_ui_lang
  200. # regions (aka "market codes")
  201. engine_traits.regions['zh-CN'] = 'zh-cn'
  202. map_market_codes = {
  203. 'zh-hk': 'en-hk', # not sure why, but at M$ this is the market code for Hongkong
  204. }
  205. for href in eval_xpath(dom, '//div[@id="region-section-content"]//div[@class="regionItem"]/a/@href'):
  206. cc_tag = parse_qs(urlparse(href).query)['cc'][0]
  207. if cc_tag == 'clear':
  208. engine_traits.all_locale = cc_tag
  209. continue
  210. # add market codes from official languages of the country ..
  211. for lang_tag in babel.languages.get_official_languages(cc_tag, de_facto=True):
  212. if lang_tag not in engine_traits.languages.keys():
  213. # print("ignore lang: %s <-- %s" % (cc_tag, lang_tag))
  214. continue
  215. lang_tag = lang_tag.split('_')[0] # zh_Hant --> zh
  216. market_code = f"{lang_tag}-{cc_tag}" # zh-tw
  217. market_code = map_market_codes.get(market_code, market_code)
  218. sxng_tag = region_tag(babel.Locale.parse('%s_%s' % (lang_tag, cc_tag.upper())))
  219. conflict = engine_traits.regions.get(sxng_tag)
  220. if conflict:
  221. if conflict != market_code:
  222. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, market_code))
  223. continue
  224. engine_traits.regions[sxng_tag] = market_code