yahoo_news.py 2.5 KB

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