bing.py 6.2 KB

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