bing.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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
  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. for i, result in enumerate(eval_xpath_list(dom, '//li[contains(@class, "b_algo")]')):
  64. link = eval_xpath(result, './/h2/a')[0]
  65. url = link.attrib.get('href')
  66. title = extract_text(link)
  67. # Make sure that the element is free of <a href> links and <span class='algoSlug_icon'>
  68. content = eval_xpath(result, '(.//p)[1]')
  69. for p in content:
  70. for e in p.xpath('.//a'):
  71. e.getparent().remove(e)
  72. for e in p.xpath('.//span[@class="algoSlug_icon"]'):
  73. e.getparent().remove(e)
  74. content = extract_text(content)
  75. # get the real URL either using the URL shown to user or following the Bing URL
  76. if url.startswith('https://www.bing.com/ck/a?'):
  77. url_cite = extract_text(eval_xpath(result, './/div[@class="b_attribution"]/cite'))
  78. # Bing can shorten the URL either at the end or in the middle of the string
  79. if (
  80. url_cite.startswith('https://')
  81. and '…' not in url_cite
  82. and '...' not in url_cite
  83. and '›' not in url_cite
  84. ):
  85. # no need for an additional HTTP request
  86. url = url_cite
  87. else:
  88. # resolve the URL with an additional HTTP request
  89. url_to_resolve.append(url.replace('&ntb=1', '&ntb=F'))
  90. url_to_resolve_index.append(i)
  91. url = None # remove the result if the HTTP Bing redirect raise an exception
  92. # append result
  93. results.append({'url': url, 'title': title, 'content': content})
  94. # resolve all Bing redirections in parallel
  95. request_list = [
  96. Request.get(u, allow_redirects=False, headers=resp.search_params['headers']) for u in url_to_resolve
  97. ]
  98. response_list = multi_requests(request_list)
  99. for i, redirect_response in enumerate(response_list):
  100. if not isinstance(redirect_response, Exception):
  101. results[url_to_resolve_index[i]]['url'] = redirect_response.headers['location']
  102. # get number_of_results
  103. try:
  104. result_len_container = "".join(eval_xpath(dom, '//span[@class="sb_count"]//text()'))
  105. if "-" in result_len_container:
  106. # Remove the part "from-to" for paginated request ...
  107. result_len_container = result_len_container[result_len_container.find("-") * 2 + 2 :]
  108. result_len_container = re.sub('[^0-9]', '', result_len_container)
  109. if len(result_len_container) > 0:
  110. result_len = int(result_len_container)
  111. except Exception as e: # pylint: disable=broad-except
  112. logger.debug('result error :\n%s', e)
  113. if result_len and _get_offset_from_pageno(resp.search_params.get("pageno", 0)) > result_len:
  114. return []
  115. results.append({'number_of_results': result_len})
  116. return results
  117. # get supported languages from their site
  118. def _fetch_supported_languages(resp):
  119. lang_tags = set()
  120. dom = html.fromstring(resp.text)
  121. lang_links = eval_xpath(dom, '//div[@id="language-section"]//li')
  122. for _li in lang_links:
  123. href = eval_xpath(_li, './/@href')[0]
  124. (_scheme, _netloc, _path, _params, query, _fragment) = urlparse(href)
  125. query = parse_qs(query, keep_blank_values=True)
  126. # fmt: off
  127. setlang = query.get('setlang', [None, ])[0]
  128. # example: 'mn-Cyrl-MN' --> '['mn', 'Cyrl-MN']
  129. lang, nation = (setlang.split('-', maxsplit=1) + [None,])[:2] # fmt: skip
  130. # fmt: on
  131. tag = lang + '-' + nation if nation else lang
  132. lang_tags.add(tag)
  133. return list(lang_tags)