yahoo_news.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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())) # noqa
  38. else:
  39. if re.match("^[0-9]+ hour(s|), [0-9]+ minute(s|) ago$",
  40. publishedDate):
  41. timeNumbers = re.findall(r'\d+', publishedDate)
  42. publishedDate = datetime.now()\
  43. - timedelta(hours=int(timeNumbers[0]))\
  44. - timedelta(minutes=int(timeNumbers[1]))
  45. else:
  46. # TODO year in string possible?
  47. publishedDate = datetime.strptime(publishedDate,
  48. "%b %d %H:%M%p")
  49. if publishedDate.year == 1900:
  50. publishedDate = publishedDate.replace(year=datetime.now().year)
  51. results.append({'url': url,
  52. 'title': title,
  53. 'content': content,
  54. 'publishedDate': publishedDate})
  55. if not suggestion_xpath:
  56. return results
  57. for suggestion in dom.xpath(suggestion_xpath):
  58. results.append({'suggestion': extract_text(suggestion)})
  59. return results