bing_news.py 1.6 KB

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