bing.py 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. ## Bing (Web)
  2. #
  3. # @website https://www.bing.com
  4. # @provide-api yes (http://datamarket.azure.com/dataset/bing/search),
  5. # max. 5000 query/month
  6. #
  7. # @using-api no (because of query limit)
  8. # @results HTML (using search portal)
  9. # @stable no (HTML can change)
  10. # @parse url, title, content
  11. #
  12. # @todo publishedDate
  13. from urllib import urlencode
  14. from cgi import escape
  15. from lxml import html
  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.content)
  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 = ' '.join(link.xpath('.//text()'))
  46. content = escape(' '.join(result.xpath('.//p//text()')))
  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 = ' '.join(link.xpath('.//text()'))
  59. content = escape(' '.join(result.xpath('.//p//text()')))
  60. # append result
  61. results.append({'url': url,
  62. 'title': title,
  63. 'content': content})
  64. # return results
  65. return results