bing.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from urllib import urlencode
  2. from cgi import escape
  3. from lxml import html
  4. base_url = 'http://www.bing.com/'
  5. search_string = 'search?{query}&first={offset}'
  6. paging = True
  7. language_support = True
  8. def request(query, params):
  9. offset = (params['pageno'] - 1) * 10 + 1
  10. if params['language'] == 'all':
  11. language = 'en-US'
  12. else:
  13. language = params['language'].replace('_', '-')
  14. search_path = search_string.format(
  15. query=urlencode({'q': query, 'setmkt': language}),
  16. offset=offset)
  17. params['cookies']['SRCHHPGUSR'] = \
  18. 'NEWWND=0&NRSLT=-1&SRCHLANG=' + language.split('-')[0]
  19. #if params['category'] == 'images':
  20. # params['url'] = base_url + 'images/' + search_path
  21. params['url'] = base_url + search_path
  22. return params
  23. def response(resp):
  24. results = []
  25. dom = html.fromstring(resp.content)
  26. for result in dom.xpath('//div[@class="sa_cc"]'):
  27. link = result.xpath('.//h3/a')[0]
  28. url = link.attrib.get('href')
  29. title = ' '.join(link.xpath('.//text()'))
  30. content = escape(' '.join(result.xpath('.//p//text()')))
  31. results.append({'url': url, 'title': title, 'content': content})
  32. if results:
  33. return results
  34. for result in dom.xpath('//li[@class="b_algo"]'):
  35. link = result.xpath('.//h2/a')[0]
  36. url = link.attrib.get('href')
  37. title = ' '.join(link.xpath('.//text()'))
  38. content = escape(' '.join(result.xpath('.//p//text()')))
  39. results.append({'url': url, 'title': title, 'content': content})
  40. return results