yahoo_news.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python
  2. from urllib import urlencode
  3. from lxml import html
  4. from searx.engines.xpath import extract_text, extract_url
  5. from searx.engines.yahoo import parse_url
  6. from datetime import datetime, timedelta
  7. import re
  8. categories = ['news']
  9. search_url = 'http://news.search.yahoo.com/search?{query}&b={offset}'
  10. results_xpath = '//div[@class="res"]'
  11. url_xpath = './/h3/a/@href'
  12. title_xpath = './/h3/a'
  13. content_xpath = './/div[@class="abstr"]'
  14. publishedDate_xpath = './/span[@class="timestamp"]'
  15. suggestion_xpath = '//div[@id="satat"]//a'
  16. paging = True
  17. def request(query, params):
  18. offset = (params['pageno'] - 1) * 10 + 1
  19. if params['language'] == 'all':
  20. language = 'en'
  21. else:
  22. language = params['language'].split('_')[0]
  23. params['url'] = search_url.format(offset=offset,
  24. query=urlencode({'p': query}))
  25. params['cookies']['sB'] = 'fl=1&vl=lang_{lang}&sh=1&rw=new&v=1'\
  26. .format(lang=language)
  27. return params
  28. def response(resp):
  29. results = []
  30. dom = html.fromstring(resp.text)
  31. for result in dom.xpath(results_xpath):
  32. url = parse_url(extract_url(result.xpath(url_xpath), search_url))
  33. title = extract_text(result.xpath(title_xpath)[0])
  34. content = extract_text(result.xpath(content_xpath)[0])
  35. publishedDate = extract_text(result.xpath(publishedDate_xpath)[0])
  36. if re.match("^[0-9]+ minute(s|) ago$", publishedDate):
  37. publishedDate = datetime.now() - timedelta(minutes=int(re.match(r'\d+', publishedDate).group()))
  38. else:
  39. if re.match("^[0-9]+ hour(s|), [0-9]+ minute(s|) ago$", publishedDate):
  40. timeNumbers = re.findall(r'\d+', publishedDate)
  41. publishedDate = datetime.now() - timedelta(hours=int(timeNumbers[0])) - timedelta(minutes=int(timeNumbers[1]))
  42. else:
  43. # TODO year in string possible?
  44. publishedDate = datetime.strptime(publishedDate,"%b %d %H:%M%p")
  45. if publishedDate.year == 1900:
  46. publishedDate = publishedDate.replace(year=datetime.now().year)
  47. results.append({'url': url, 'title': title, 'content': content,'publishedDate':publishedDate})
  48. if not suggestion_xpath:
  49. return results
  50. for suggestion in dom.xpath(suggestion_xpath):
  51. results.append({'suggestion': extract_text(suggestion)})
  52. return results