bing.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. """
  2. Bing (Web)
  3. @website https://www.bing.com
  4. @provide-api yes (http://datamarket.azure.com/dataset/bing/search),
  5. max. 5000 query/month
  6. @using-api no (because of query limit)
  7. @results HTML (using search portal)
  8. @stable no (HTML can change)
  9. @parse url, title, content
  10. @todo publishedDate
  11. """
  12. from urllib import urlencode
  13. from cgi import escape
  14. from lxml import html
  15. from searx.engines.xpath import extract_text
  16. # engine dependent config
  17. categories = ['general']
  18. paging = True
  19. language_support = True
  20. # search-url
  21. base_url = 'https://www.bing.com/'
  22. search_string = 'search?{query}&first={offset}'
  23. # do search-request
  24. def request(query, params):
  25. offset = (params['pageno'] - 1) * 10 + 1
  26. if params['language'] == 'all':
  27. language = 'en-US'
  28. else:
  29. language = params['language'].replace('_', '-')
  30. search_path = search_string.format(
  31. query=urlencode({'q': query, 'setmkt': language}),
  32. offset=offset)
  33. params['cookies']['SRCHHPGUSR'] = \
  34. 'NEWWND=0&NRSLT=-1&SRCHLANG=' + language.split('-')[0]
  35. params['url'] = base_url + search_path
  36. return params
  37. # get response from search-request
  38. def response(resp):
  39. results = []
  40. dom = html.fromstring(resp.text)
  41. # parse results
  42. for result in dom.xpath('//div[@class="sa_cc"]'):
  43. link = result.xpath('.//h3/a')[0]
  44. url = link.attrib.get('href')
  45. title = extract_text(link)
  46. content = escape(extract_text(result.xpath('.//p')))
  47. # append result
  48. results.append({'url': url,
  49. 'title': title,
  50. 'content': content})
  51. # return results if something is found
  52. if results:
  53. return results
  54. # parse results again if nothing is found yet
  55. for result in dom.xpath('//li[@class="b_algo"]'):
  56. link = result.xpath('.//h2/a')[0]
  57. url = link.attrib.get('href')
  58. title = extract_text(link)
  59. content = escape(extract_text(result.xpath('.//p')))
  60. # append result
  61. results.append({'url': url,
  62. 'title': title,
  63. 'content': content})
  64. # return results
  65. return results