service.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Licensed to the Software Freedom Conservancy (SFC) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The SFC licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. import os
  18. import tempfile
  19. from selenium.webdriver.common import service
  20. class Service(service.Service):
  21. """
  22. Object that manages the starting and stopping of PhantomJS / Ghostdriver
  23. """
  24. def __init__(self, executable_path, port=0, service_args=None, log_path=None):
  25. """
  26. Creates a new instance of the Service
  27. :Args:
  28. - executable_path : Path to PhantomJS binary
  29. - port : Port the service is running on
  30. - service_args : A List of other command line options to pass to PhantomJS
  31. - log_path: Path for PhantomJS service to log to
  32. """
  33. self.service_args = service_args
  34. if self.service_args is None:
  35. self.service_args = []
  36. else:
  37. self.service_args = service_args[:]
  38. if not log_path:
  39. log_path = "ghostdriver.log"
  40. if not self._args_contain("--cookies-file="):
  41. self._cookie_temp_file_handle, self._cookie_temp_file = tempfile.mkstemp()
  42. self.service_args.append("--cookies-file=" + self._cookie_temp_file)
  43. else:
  44. self._cookie_temp_file = None
  45. service.Service.__init__(self, executable_path, port=port, log_file=open(log_path, 'w'))
  46. def _args_contain(self, arg):
  47. return len(list(filter(lambda x: x.startswith(arg), self.service_args))) > 0
  48. def command_line_args(self):
  49. return self.service_args + ["--webdriver=%d" % self.port]
  50. @property
  51. def service_url(self):
  52. """
  53. Gets the url of the GhostDriver Service
  54. """
  55. return "http://localhost:%d/wd/hub" % self.port
  56. def send_remote_shutdown_command(self):
  57. if self._cookie_temp_file:
  58. os.close(self._cookie_temp_file_handle)
  59. os.remove(self._cookie_temp_file)