casperjsTest.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import time
  2. import platform
  3. import os
  4. import subprocess
  5. class Main:
  6. def __init__(self, url, outputFilePath):
  7. self.url = url
  8. self.outputFilePath = outputFilePath
  9. # temp file name
  10. self.fileName = str(time.time()) + ".html"
  11. def _is_windows(self):
  12. if "Windows" in str(platform.uname()):
  13. return True
  14. else:
  15. return False
  16. def run(self):
  17. if self._is_windows():
  18. proc = subprocess.Popen(["cmd", "/c", "casperjs %s/site.js --url=%s --outputfile=%s" % (self.outputFilePath, self.url, self.fileName) ], stdout=subprocess.PIPE)
  19. else:
  20. proc = subprocess.Popen(["bash", "-c", "cd %s && casperjs site.js --url=%s --outputfile=%s" % (self.outputFilePath, self.url, self.fileName) ], stdout=subprocess.PIPE)
  21. out = proc.communicate()[0]
  22. htmlFileName = ''
  23. # 因为输出路径在windows不确定,所以这里加了所有可能的路径判断
  24. if os.path.isfile(self.fileName):
  25. htmlFileName = self.fileName
  26. elif os.path.isfile(os.path.join(self.outputFilePath, self.fileName)):
  27. htmlFileName = os.path.join(self.outputFilePath, self.fileName)
  28. elif os.path.isfile(os.path.join(os.path.dirname(os.path.realpath(__file__)), self.fileName)):
  29. htmlFileName = os.path.join(os.path.dirname(os.path.realpath(__file__)), self.fileName)
  30. if (not os.path.isfile(htmlFileName)):
  31. print('Failed to get html content from ', self.url)
  32. if __name__ == '__main__':
  33. Main(url="http://www.mouser.cn/Mobile/",
  34. outputFilePath="C:\\SourcePython\\uuspider\\test").run();