bing.py 1.4 KB

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