bing.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Bing (Web)
  4. - https://github.com/searx/searx/issues/2019#issuecomment-648227442
  5. """
  6. import re
  7. from urllib.parse import urlencode, urlparse, parse_qs
  8. from lxml import html
  9. from searx.utils import eval_xpath, extract_text, eval_xpath_list, match_language
  10. from searx.network import multi_requests, Request
  11. about = {
  12. "website": 'https://www.bing.com',
  13. "wikidata_id": 'Q182496',
  14. "official_api_documentation": 'https://www.microsoft.com/en-us/bing/apis/bing-web-search-api',
  15. "use_official_api": False,
  16. "require_api_key": False,
  17. "results": 'HTML',
  18. }
  19. # engine dependent config
  20. categories = ['general', 'web']
  21. paging = True
  22. time_range_support = False
  23. safesearch = False
  24. send_accept_language_header = True
  25. supported_languages_url = 'https://www.bing.com/account/general'
  26. language_aliases = {}
  27. # search-url
  28. base_url = 'https://www.bing.com/'
  29. # initial query: https://www.bing.com/search?q=foo&search=&form=QBLH
  30. inital_query = 'search?{query}&search=&form=QBLH'
  31. # following queries: https://www.bing.com/search?q=foo&search=&first=11&FORM=PERE
  32. page_query = 'search?{query}&search=&first={offset}&FORM=PERE'
  33. def _get_offset_from_pageno(pageno):
  34. return (pageno - 1) * 10 + 1
  35. def request(query, params):
  36. offset = _get_offset_from_pageno(params.get('pageno', 1))
  37. # logger.debug("params['pageno'] --> %s", params.get('pageno'))
  38. # logger.debug(" offset --> %s", offset)
  39. search_string = page_query
  40. if offset == 1:
  41. search_string = inital_query
  42. if params['language'] == 'all':
  43. lang = 'EN'
  44. else:
  45. lang = match_language(params['language'], supported_languages, language_aliases)
  46. query = 'language:{} {}'.format(lang.split('-')[0].upper(), query)
  47. search_path = search_string.format(query=urlencode({'q': query}), offset=offset)
  48. if offset > 1:
  49. referer = base_url + inital_query.format(query=urlencode({'q': query}))
  50. params['headers']['Referer'] = referer
  51. logger.debug("headers.Referer --> %s", referer)
  52. params['url'] = base_url + search_path
  53. params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  54. return params
  55. def response(resp):
  56. results = []
  57. result_len = 0
  58. dom = html.fromstring(resp.text)
  59. # parse results again if nothing is found yet
  60. url_to_resolve = []
  61. url_to_resolve_index = []
  62. for i, result in enumerate(eval_xpath_list(dom, '//li[@class="b_algo"]')):
  63. link = eval_xpath(result, './/h2/a')[0]
  64. url = link.attrib.get('href')
  65. title = extract_text(link)
  66. content = extract_text(eval_xpath(result, './/p'))
  67. # get the real URL either using the URL shown to user or following the Bing URL
  68. if url.startswith('https://www.bing.com/ck/a?'):
  69. url_cite = extract_text(eval_xpath(result, './/div[@class="b_attribution"]/cite'))
  70. # Bing can shorten the URL either at the end or in the middle of the string
  71. if (
  72. url_cite.startswith('https://')
  73. and '…' not in url_cite
  74. and '...' not in url_cite
  75. and '›' not in url_cite
  76. ):
  77. # no need for an additional HTTP request
  78. url = url_cite
  79. else:
  80. # resolve the URL with an additional HTTP request
  81. url_to_resolve.append(url.replace('&ntb=1', '&ntb=F'))
  82. url_to_resolve_index.append(i)
  83. url = None # remove the result if the HTTP Bing redirect raise an exception
  84. # append result
  85. results.append({'url': url, 'title': title, 'content': content})
  86. # resolve all Bing redirections in parallel
  87. request_list = [
  88. Request.get(u, allow_redirects=False, headers=resp.search_params['headers']) for u in url_to_resolve
  89. ]
  90. response_list = multi_requests(request_list)
  91. for i, redirect_response in enumerate(response_list):
  92. if not isinstance(redirect_response, Exception):
  93. results[url_to_resolve_index[i]]['url'] = redirect_response.headers['location']
  94. # get number_of_results
  95. try:
  96. result_len_container = "".join(eval_xpath(dom, '//span[@class="sb_count"]//text()'))
  97. if "-" in result_len_container:
  98. # Remove the part "from-to" for paginated request ...
  99. result_len_container = result_len_container[result_len_container.find("-") * 2 + 2 :]
  100. result_len_container = re.sub('[^0-9]', '', result_len_container)
  101. if len(result_len_container) > 0:
  102. result_len = int(result_len_container)
  103. except Exception as e: # pylint: disable=broad-except
  104. logger.debug('result error :\n%s', e)
  105. if result_len and _get_offset_from_pageno(resp.search_params.get("pageno", 0)) > result_len:
  106. return []
  107. results.append({'number_of_results': result_len})
  108. return results
  109. # get supported languages from their site
  110. def _fetch_supported_languages(resp):
  111. lang_tags = set()
  112. dom = html.fromstring(resp.text)
  113. lang_links = eval_xpath(dom, '//div[@id="language-section"]//li')
  114. for _li in lang_links:
  115. href = eval_xpath(_li, './/@href')[0]
  116. (_scheme, _netloc, _path, _params, query, _fragment) = urlparse(href)
  117. query = parse_qs(query, keep_blank_values=True)
  118. # fmt: off
  119. setlang = query.get('setlang', [None, ])[0]
  120. # example: 'mn-Cyrl-MN' --> '['mn', 'Cyrl-MN']
  121. lang, nation = (setlang.split('-', maxsplit=1) + [None,])[:2] # fmt: skip
  122. # fmt: on
  123. tag = lang + '-' + nation if nation else lang
  124. lang_tags.add(tag)
  125. return list(lang_tags)