bing.py 10 KB

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