bing.py 2.2 KB

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