Exemple #1
0
    def __init__(self, executable_path, port=0, quiet=False, service_args=None):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to the SafariDriver
         - port : Port the service is running on
         - quiet : Suppress driver stdout and stderr
         - service_args : List of args to pass to the safaridriver service """

        if not os.path.exists(executable_path):
            if "Safari Technology Preview" in executable_path:
                message = "Safari Technology Preview does not seem to be installed. You can download it at https://developer.apple.com/safari/download/."
            else:
                message = "SafariDriver was not found; are you running Safari 10 or later? You can download Safari at https://developer.apple.com/safari/download/."
            raise Exception(message)

        if port == 0:
            port = utils.free_port()

        self.service_args = service_args or []

        self.quiet = quiet
        log = PIPE
        if quiet:
            log = open(os.devnull, 'w')
        service.Service.__init__(self, executable_path, port, log)
Exemple #2
0
    def __init__(self, executable_path='IEDriverServer.exe', capabilities=None,
                 port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT, host=DEFAULT_HOST,
                 log_level=DEFAULT_LOG_LEVEL, log_file=DEFAULT_LOG_FILE):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()
        self.host = host
        self.log_level = log_level
        self.log_file = log_file

        self.iedriver = Service(
            executable_path,
            port=self.port,
            host=self.host,
            log_level=self.log_level,
            log_file=self.log_file)

        self.iedriver.start()

        if capabilities is None:
            capabilities = DesiredCapabilities.INTERNETEXPLORER

        RemoteWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=capabilities)
        self._is_remote = False
Exemple #3
0
    def __init__(self, executable_path='IEDriverServer.exe', 
                    port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        try:
            self.iedriver = Service(executable_path, port=self.port)
            self.iedriver.start()
        except:
            # Create IE Driver instance of the unmanaged code
            try:
                warnings.warn("You need to download the IEDriverServer. \
                            Using the deprecated approach", DeprecationWarning)
                self.iedriver = CDLL(os.path.join(os.path.dirname(__file__),"win32", "IEDriver.dll"))
            except WindowsError:
                try:
                    self.iedriver = CDLL(os.path.join(os.path.dirname(__file__),"x64", "IEDriver.dll"))
                except WindowsError:
                    raise WebDriverException("Unable to load the IEDriver.dll component")
            self.ptr = self.iedriver.StartServer(self.port)

            seconds = 0
            while not utils.is_url_connectable(self.port):
                seconds += 1
                if seconds > DEFAULT_TIMEOUT:
                    # Clean up after ourselves
                    self.quit()
                    raise RuntimeError("Unable to connect to IE")
                time.sleep(1)

        RemoteWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=DesiredCapabilities.INTERNETEXPLORER)
 def setUpClass(cls):
     super(TBStemTest, cls).setUpClass()
     cls.control_port = free_port()
     cls.socks_port = free_port()
     temp_data_dir = tempfile.mkdtemp()
     torrc = {'ControlPort': str(cls.control_port),
              'SOCKSPort': str(cls.socks_port),
              'DataDirectory': temp_data_dir}
     cls.tor_process = launch_tbb_tor_with_stem_fixture(tbb_path=TBB_PATH,
                                                        torrc=torrc)
     cls.controller = Controller.from_port(port=cls.control_port)
     cls.controller.authenticate()
     cls.driver = TBDriverFixture(TBB_PATH,
                                  tor_cfg=cm.USE_RUNNING_TOR,
                                  socks_port=cls.socks_port,
                                  control_port=cls.control_port)
Exemple #5
0
    def __init__(self, executable_path, port=0, service_args=None, log_path=None):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to PhantomJS binary
         - port : Port the service is running on
         - service_args : A List of other command line options to pass to PhantomJS
         - log_path: Path for PhantomJS service to log to
        """

        self.port = port
        self.path = executable_path
        self.service_args= service_args
        if self.port == 0:
            self.port = utils.free_port()
        if self.service_args is None:
            self.service_args = []
        else:
            self.service_args=service_args[:]
        self.service_args.insert(0, self.path)
        self.service_args.append("--webdriver=%d" % self.port)
        self.process = None
        if not log_path:
            log_path = "ghostdriver.log"
        self._log = open(log_path, 'w')
    def __init__(self, port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        # Create IE Driver instance of the unmanaged code
        try:
            self.iedriver = CDLL(os.path.join(os.path.dirname(__file__),"win32", "IEDriver.dll"))
        except WindowsError:
            try:
                self.iedriver = CDLL(os.path.join(os.path.dirname(__file__),"x64", "IEDriver.dll"))
            except WindowsError:
                raise WebDriverException("Unable to load the IEDriver.dll component")
        self.ptr = self.iedriver.StartServer(self.port)

        seconds = 0
        while not utils.is_connectable(self.port):
            seconds += 1
            if seconds > DEFAULT_TIMEOUT:
                raise RuntimeError("Unable to connect to IE")
            time.sleep(1)

        RemoteWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=DesiredCapabilities.INTERNETEXPLORER)
    def test_should_not_load_with_wrong_sys_socks_port(self):
        socks_port = free_port()
        with self.assertRaises(TBDriverPortError) as exc:
            TorBrowserDriver(TBB_PATH, socks_port=socks_port,
                             tor_cfg=cm.USE_RUNNING_TOR)

        self.assertEqual(str(exc.exception),
                         "SOCKS port %s is not listening" % socks_port)
Exemple #8
0
    def __init__(self, executable_path='IEDriverServer.exe', capabilities=None,
                 port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT, host=DEFAULT_HOST,
                 log_level=DEFAULT_LOG_LEVEL, service_log_path=DEFAULT_SERVICE_LOG_PATH, options=None,
                 ie_options=None, desired_capabilities=None, log_file=None):
        """
        Creates a new instance of the chrome driver.

        Starts the service and then creates new instance of chrome driver.

        :Args:
         - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
         - capabilities: capabilities Dictionary object
         - port - port you would like the service to run, if left as 0, a free port will be found.
         - log_level - log level you would like the service to run.
         - service_log_path - target of logging of service, may be "stdout", "stderr" or file path.
         - options: IE Options instance, providing additional IE options
         - desired_capabilities: alias of capabilities; this will make the signature consistent with RemoteWebDriver.
        """
        if log_file:
            warnings.warn('use service_log_path instead of log_file', DeprecationWarning)
            service_log_path = log_file
        if ie_options:
            warnings.warn('use options instead of ie_options', DeprecationWarning)
            options = ie_options
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()
        self.host = host

        # If both capabilities and desired capabilities are set, ignore desired capabilities.
        if capabilities is None and desired_capabilities:
            capabilities = desired_capabilities

        if options is None:
            if capabilities is None:
                capabilities = self.create_options().to_capabilities()
        else:
            if capabilities is None:
                capabilities = options.to_capabilities()
            else:
                # desired_capabilities stays as passed in
                capabilities.update(options.to_capabilities())

        self.iedriver = Service(
            executable_path,
            port=self.port,
            host=self.host,
            log_level=log_level,
            log_file=service_log_path)

        self.iedriver.start()

        RemoteWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=capabilities)
        self._is_remote = False
    def __init__(self, executable_path, port=0):
        """ Creates a new instance of the Service
            Args:
                executable_path : Path to the ChromeDriver
                port : Port the service is running on """

        self.port = port
        self.path = executable_path
        if self.port == 0:
            self.port = utils.free_port()
Exemple #10
0
    def __init__(self, executable, port=0, log_file=PIPE, env=None, start_error_message=""):
        self.path = executable

        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        self.start_error_message = start_error_message
        self.log_file = log_file
        self.env = env or os.environ
Exemple #11
0
    def __init__(self, executable_path='IEDriverServer.exe', capabilities=None,
                 port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT, host=DEFAULT_HOST,
                 log_level=DEFAULT_LOG_LEVEL, log_file=DEFAULT_LOG_FILE, options=None,
                 ie_options=None):
        """
        Creates a new instance of the chrome driver.

        Starts the service and then creates new instance of chrome driver.

        :Args:
         - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
         - capabilities: capabilities Dictionary object
         - port - port you would like the service to run, if left as 0, a free port will be found.
         - log_level - log level you would like the service to run.
         - log_file - log file you would like the service to log to.
         - options: IE Options instance, providing additional IE options
        """
        if ie_options:
            warnings.warn('use options instead of ie_options', DeprecationWarning)
            options = ie_options
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()
        self.host = host
        self.log_level = log_level
        self.log_file = log_file

        if options is None:
            # desired_capabilities stays as passed in
            if capabilities is None:
                capabilities = self.create_options().to_capabilities()
        else:
            if capabilities is None:
                capabilities = options.to_capabilities()
            else:
                capabilities.update(options.to_capabilities())

        self.iedriver = Service(
            executable_path,
            port=self.port,
            host=self.host,
            log_level=self.log_level,
            log_file=self.log_file)

        self.iedriver.start()

        if capabilities is None:
            capabilities = DesiredCapabilities.INTERNETEXPLORER

        RemoteWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=capabilities)
        self._is_remote = False
Exemple #12
0
 def setUp(self):
     self.wd = get_webdriver()
     self.port = free_port()
     cmd = [sys.executable, '-m', self.module, '--port', str(self.port)]
     self.proc = subprocess.Popen(cmd, env=os.environ,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE,
                                  )
     self.url = 'http://localhost:{}'.format(self.port)
     time.sleep(0.5)
     self.wd.get(self.url)
    def __init__(self):
        """
        Default constructor

        ARGS:
            None
        RETURNS:
            None
        """
        self.browser = PhantomJS(executable_path='./drivers/phantomjs',
                                 port=free_port())  # Optional argument, if not specified will search path.
        self.timeout = 5 # seconds
 def __init__(self, device=None, port=0):
     """ Creates a new instance of the Service
         Args:
             device: serial ID of the Android device.
                     Could be seen by command 'android devices'.
                     If only one device connected. you do not need to assign it
     """
     self.device = Service.initDevice(device)
     self.adbCmd = r"adb -s %s " % self.device
     self.port = port
     if self.port == 0:
         self.port = utils.free_port()
Exemple #15
0
    def __init__(self, executable, port=0, log_file=DEVNULL, env=None, start_error_message=""):
        self.path = executable

        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        if not _HAS_NATIVE_DEVNULL and log_file == DEVNULL:
            log_file = open(os.devnull, 'wb')

        self.start_error_message = start_error_message
        self.log_file = log_file
        self.env = env or os.environ
Exemple #16
0
    def __init__(self, executable_path='IEDriverServer.exe', 
                    port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        self.iedriver = Service(executable_path, port=self.port)
        self.iedriver.start()

        RemoteWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=DesiredCapabilities.INTERNETEXPLORER)
Exemple #17
0
    def __init__(self, executable_path, port=0, service_args=None):
        """
        Creates a new instance of the Service
        
        :Args:
         - executable_path : Path to the ChromeDriver
         - port : Port the service is running on """

        self.port = port
        self.path = executable_path
        self.service_args= service_args
        if self.port == 0:
            self.port = utils.free_port()
    def __init__(self, executable_path, port=0, quiet=False):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to the SafariDriver
         - port : Port the service is running on """

        self.port = port
        self.path = executable_path
        if self.port == 0:
            self.port = utils.free_port()
        self.quiet = quiet
def launch_tb_with_custom_stem(tbb_dir):
    socks_port = free_port()
    control_port = free_port()
    tor_data_dir = tempfile.mkdtemp()
    tor_binary = join(tbb_dir, cm.DEFAULT_TOR_BINARY_PATH)
    print("SOCKS port: %s, Control port: %s" % (socks_port, control_port))

    torrc = {'ControlPort': str(control_port),
             'SOCKSPort': str(socks_port),
             'DataDirectory': tor_data_dir}
    tor_process = launch_tbb_tor_with_stem(tbb_path=tbb_dir, torrc=torrc,
                                           tor_binary=tor_binary)
    with Controller.from_port(port=control_port) as controller:
        controller.authenticate()
        with TorBrowserDriver(tbb_dir, socks_port=socks_port,
                              control_port=control_port,
                              tor_cfg=cm.USE_STEM) as driver:
            driver.load_url("https://check.torproject.org", wait_on_page=3)
            print(driver.find_element_by("h1.on").text)
            print(driver.find_element_by(".content > p").text)
        print_tor_circuits(controller)

    tor_process.kill()
Exemple #20
0
    def __init__(self, executable_path='MicrosoftWebDriver.exe',
                 desired_capabilities=DesiredCapabilities.EDGE, port=0):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        self.edge_service = Service(executable_path, port=self.port)
        self.edge_service.start()

        RemoteWebDriver.__init__(
            self,
            command_executor=RemoteConnection('http://localhost:%d' % self.port,
                                              resolve_ip=False),
            desired_capabilities=desired_capabilities)
        self._is_remote = False
Exemple #21
0
    def __init__(self, executable_path='MicrosoftWebDriver.exe',
                 capabilities=None, port=0):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        self.edge_service = Service(executable_path, port=self.port)
        self.edge_service.start()

        if capabilities is None:
            capabilities = DesiredCapabilities.EDGE

        RemoteWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=capabilities)
        self._is_remote = False
Exemple #22
0
    def __init__(self, executable_path, port=0, service_args=None, log_path=None):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to the ChromeDriver
         - port : Port the service is running on
         - service_args : List of args to pass to the chromedriver service
         - log_path : Path for the chromedriver service to log to"""

        self.port = port
        self.path = executable_path
        self.service_args = service_args or []
        if log_path:
            self.service_args.append("--log-path=%s" % log_path)
        if self.port == 0:
            self.port = utils.free_port()
    def __init__(self, profile_directory=None):
        """Initialise a TBB profile.

        This will automatically choose a free port and add the TorButton,
        TorLauncher, and NoScript addons. The HTTPSEverywhere addon is not
        added because it is a directory, not an .xpi file, in TBB's profile
        directory, and thus there isn't an easy way to add it to a Selecium
        :class:`webdriver.FirefoxProfile` instance.
        """
        if profile_directory is None:
            profile_directory = TBB_PROFILE

        super(TorBrowserProfile, self).__init__(profile_directory)

        for ext in [TORBUTTON_XPI, TORLAUNCHER_XPI, NOSCRIPT_XPI]:
            self.add_extension(ext)

        self.port = free_port()
Exemple #24
0
    def __init__(self, executable_path='MicrosoftWebDriver.exe',
                 capabilities=None, port=0, verbose=False, log_path=None):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        self.edge_service = Service(executable_path, port=self.port, verbose=verbose, log_path=log_path)
        self.edge_service.start()

        if capabilities is None:
            capabilities = DesiredCapabilities.EDGE

        RemoteWebDriver.__init__(
            self,
            command_executor=RemoteConnection('http://localhost:%d' % self.port,
                                              resolve_ip=False),
            desired_capabilities=capabilities)
        self._is_remote = False
Exemple #25
0
    def __init__(self,
                 executable,
                 port=0,
                 log_file=DEVNULL,
                 env=None,
                 start_error_message=""):
        self.path = executable

        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        if not _HAS_NATIVE_DEVNULL and log_file == DEVNULL:
            log_file = open(os.devnull, 'wb')

        self.start_error_message = start_error_message
        self.log_file = log_file
        self.env = env or os.environ
Exemple #26
0
    def __init__(self,
                 executable_path='MicrosoftWebDriver.exe',
                 capabilities=None,
                 port=0):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        self.edge_service = Service(executable_path, port=self.port)
        self.edge_service.start()

        if capabilities is None:
            capabilities = DesiredCapabilities.EDGE

        RemoteWebDriver.__init__(self,
                                 command_executor='http://localhost:%d' %
                                 self.port,
                                 desired_capabilities=capabilities)
        self._is_remote = False
Exemple #27
0
    def __init__(self, executable_path, firefox_binary=None, port=0, service_args=None,
                 log_path=None, env=None):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to the GeckoDriver
         - port : Port the service is running on
         - service_args : List of args to pass to the Geckodriver service
         - log_path : Path for the GeckoDriver service to log to"""

        self.port = port
        self.path = executable_path
        self.firefox_binary = firefox_binary
        self.service_args = service_args or []

        if self.port == 0:
            self.port = utils.free_port()
        self.env = env
Exemple #28
0
 def setUp(self):
     super().setUp()
     self.port = free_port()
     env = os.environ.copy()
     env['PYTHONPATH'] = root
     _ = tempfile.NamedTemporaryFile(mode='w+', suffix='.py', delete=False)
     with _ as f:
         self.tmp = f.name
         f.write(script)
     cmd = [sys.executable, self.tmp, '--port', str(self.port)] + self.cmd
     self.url = 'http://localhost:{}'.format(self.port)
     self.ws_url = 'ws://localhost:{}/rimo_ws'.format(self.port)
     self.proc = subprocess.Popen(
         cmd, cwd=curdir, env=env,
         stdout=subprocess.PIPE,
         stderr=subprocess.STDOUT,
         universal_newlines=True,
     )
     sync(self.wait(times=10))
Exemple #29
0
    def __init__(self, executable_path, firefox_binary=None, port=0, service_args=None,
                 log_path=None, env=None):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to the GeckoDriver
         - port : Port the service is running on
         - service_args : List of args to pass to the Geckodriver service
         - log_path : Path for the GeckoDriver service to log to"""

        self.port = port
        self.path = executable_path
        self.firefox_binary = firefox_binary
        self.service_args = service_args or []

        if self.port == 0:
            self.port = utils.free_port()
        self.env = env
Exemple #30
0
    def __init__(self,
                 executable_path='IEDriverServer.exe',
                 port=DEFAULT_PORT,
                 timeout=DEFAULT_TIMEOUT):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        try:
            self.iedriver = Service(executable_path, port=self.port)
            self.iedriver.start()
        except:
            # Create IE Driver instance of the unmanaged code
            try:
                warnings.warn(
                    "You need to download the IEDriverServer. \
                            Using the deprecated approach", DeprecationWarning)
                self.iedriver = CDLL(
                    os.path.join(os.path.dirname(__file__), "win32",
                                 "IEDriver.dll"))
            except WindowsError:
                try:
                    self.iedriver = CDLL(
                        os.path.join(os.path.dirname(__file__), "x64",
                                     "IEDriver.dll"))
                except WindowsError:
                    raise WebDriverException(
                        "Unable to load the IEDriver.dll component")
            self.ptr = self.iedriver.StartServer(self.port)

            seconds = 0
            while not utils.is_url_connectable(self.port):
                seconds += 1
                if seconds > DEFAULT_TIMEOUT:
                    # Clean up after ourselves
                    self.quit()
                    raise RuntimeError("Unable to connect to IE")
                time.sleep(1)

        RemoteWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=DesiredCapabilities.INTERNETEXPLORER)
Exemple #31
0
    def start(self):
        """Start server and web driver."""
        self.wd = get_webdriver()

        def start_server(port):
            import asyncio
            from wdom import server

            server.start_server(port=port)
            asyncio.get_event_loop().run_forever()

        self.address = "localhost"
        self.port = free_port()
        self.url = "http://{0}:{1}/".format(self.address, self.port)

        self.server = Process(target=start_server, args=(self.port,))
        self.server.start()
        self.wait(times=10)
        self.wd.get(self.url)
Exemple #32
0
    def __init__(self, executable_path, port=0, quiet=False):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to the SafariDriver
         - port : Port the service is running on """

        if not os.path.exists(executable_path):
            raise Exception("SafariDriver requires Safari 10 on OSX El Capitan or greater")

        if port == 0:
            port = utils.free_port()

        self.quiet = quiet
        log = PIPE
        if quiet:
            log = open(os.devnull, 'w')
        service.Service.__init__(self, executable_path, port, log)
Exemple #33
0
    def __init__(self, executable_path, port=0, quiet=False):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to the SafariDriver
         - port : Port the service is running on """

        if not os.path.exists(executable_path):
            raise Exception("SafariDriver requires Safari 10 on OSX El Capitan or greater")

        if port == 0:
            port = utils.free_port()

        self.quiet = quiet
        log = PIPE
        if quiet:
            log = open(os.devnull, 'w')
        service.Service.__init__(self, executable_path, port, log)
Exemple #34
0
    def __init__(self,
                 executable,
                 port=0,
                 log_file=DEVNULL,
                 env=None,
                 start_error_message=""):
        self.path = executable

        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        if not _HAS_NATIVE_DEVNULL and log_file == DEVNULL:
            log_file = open(os.devnull, 'wb')

        self.start_error_message = start_error_message
        self.log_file = log_file
        self.creationflags = 0  # Default value for every python subprocess: subprocess.Popen(..., creationflags=0)
        self.env = env or os.environ
Exemple #35
0
    def __init__(self, executable_path, port=0, service_args=None,
                 log_path=None, env=None):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to the ChromeDriver
         - port : Port the service is running on
         - service_args : List of args to pass to the chromedriver service
         - log_path : Path for the chromedriver service to log to"""

        self.port = port
        self.path = executable_path
        self.service_args = service_args or []
        if log_path:
          self.service_args.append('--log-path=%s' % log_path)
        if self.port == 0:
            self.port = utils.free_port()
        self.env = env
    def __init__(self, host, firefox_profile, firefox_binary=None, timeout=30):
        self.profile = firefox_profile
        self.binary = firefox_binary
        HOST = host
        if self.binary is None:
            self.binary = FirefoxBinary()

        if HOST is None:
            HOST = "127.0.0.1"

        PORT = utils.free_port()
        self.profile.port = PORT
        self.profile.update_preferences()

        self.profile.add_extension()

        self.binary.launch_browser(self.profile)
        _URL = "http://%s:%d/hub" % (HOST, PORT)
        RemoteConnection.__init__(self, _URL, keep_alive=True)
Exemple #37
0
    def __init__(self, executable_path='IEDriverServer.exe', 
                 port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT, host=DEFAULT_HOST,
                 log_level=DEFAULT_LOG_LEVEL, log_file=DEFAULT_LOG_FILE):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()
        self.host = host
        self.log_level = log_level
        self.log_file = log_file

        self.iedriver = Service(executable_path, port=self.port,
             host=self.host, log_level=self.log_level, log_file=self.log_file)

        self.iedriver.start()

        RemoteWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=DesiredCapabilities.INTERNETEXPLORER)
Exemple #38
0
    def __init__(self,
                 executable_path='MicrosoftWebDriver.exe',
                 capabilities=None,
                 port=0,
                 verbose=False,
                 service_log_path=None,
                 log_path=None,
                 keep_alive=False):
        """
        Creates a new instance of the chrome driver.

        Starts the service and then creates new instance of chrome driver.

        :Args:
         - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
         - capabilities - Dictionary object with non-browser specific
           capabilities only, such as "proxy" or "loggingPref".
         - port - port you would like the service to run, if left as 0, a free port will be found.
         - verbose - whether to set verbose logging in the service
         - service_log_path - Where to log information from the driver.
         - keep_alive - Whether to configure ChromeRemoteConnection to use HTTP keep-alive.
         """
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        self.edge_service = Service(executable_path,
                                    port=self.port,
                                    verbose=verbose,
                                    log_path=service_log_path)
        self.edge_service.start()

        if capabilities is None:
            capabilities = DesiredCapabilities.EDGE

        RemoteWebDriver.__init__(self,
                                 command_executor=RemoteConnection(
                                     'http://localhost:%d' % self.port,
                                     resolve_ip=False,
                                     keep_alive=keep_alive),
                                 desired_capabilities=capabilities)
        self._is_remote = False
    def __init__(self, executable_path, port=0, service_args=None):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to PhantomJS binary
         - port : Port the service is running on
         - service_args : A List of other command line options to pass to PhantomJS
        """

        self.port = port
        self.path = executable_path
        self.service_args = service_args
        if self.port == 0:
            self.port = utils.free_port()
        if self.service_args is None:
            self.service_args = []
        self.service_args.insert(0, self.path)
        self.service_args.append("--webdriver=%d" % self.port)
        self._log = open("ghostdriver.log", 'w')
def start(**kwargs):
    port = str(free_port())
    devices = Command().devices_and_version()[0]
    caps = get_caps()["devices"]["samsung-10"]
    caps.update(getattr(Context, "CAPS"))
    if kwargs:
        for key, value in kwargs.items():
            caps[key] = value
    caps["deviceName"] = devices[0]
    caps["platformVersion"] = devices[1]
    service = AppiumService()
    service.start(args=["-a", "127.0.0.1", "-p", port, "--session-override"],
                  timeout_ms=2000)
    driver = webdriver.Remote(
        command_executor=f'http://127.0.0.1:{port}/wd/hub',
        desired_capabilities=caps)
    yield driver
    driver.close()
    driver.quit()
    service.stop()
Exemple #41
0
    def __init__(self, executable_path, port=0, host=None, log_level=None, log_file=None):
        """
        Creates a new instance of the Service
        
        :Args:
         - executable_path : Path to the IEDriver
         - port : Port the service is running on
         - host : IP address the service port is bound
         - log_level : Level of logging of service, may be "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE".
           Default is "FATAL".
         - log_file : Target of logging of service, may be "stdout", "stderr" or file path.
           Default is "stdout"."""

        self.port = port
        self.path = executable_path
        if self.port == 0:
            self.port = utils.free_port()
        self.host = host
        self.log_level = log_level
        self.log_file = log_file
Exemple #42
0
    def __init__(self, executable_path, port=0, host=None, log_level=None, log_file=None):
        """
        Creates a new instance of the Service
        
        :Args:
         - executable_path : Path to the IEDriver
         - port : Port the service is running on
         - host : IP address the service port is bound
         - log_level : Level of logging of service, may be "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE".
           Default is "FATAL".
         - log_file : Target of logging of service, may be "stdout", "stderr" or file path.
           Default is "stdout"."""

        self.port = port
        self.path = executable_path
        if self.port == 0:
            self.port = utils.free_port()
        self.host = host
        self.log_level = log_level
        self.log_file = log_file
Exemple #43
0
    def __init__(self, host, firefox_profile, firefox_binary=None, timeout=30):
        self.profile = firefox_profile
        self.binary = firefox_binary
        HOST = host
        if self.binary is None:
            self.binary = FirefoxBinary()

        if HOST is None:
            HOST = "127.0.0.1"

        PORT = utils.free_port()
        self.profile.port = PORT 
        self.profile.update_preferences()
        
        self.profile.add_extension()

        self.binary.launch_browser(self.profile)
        _URL = "http://%s:%d/hub" % (HOST, PORT)
        RemoteConnection.__init__(
            self, _URL, keep_alive=True)
Exemple #44
0
    def __init__(self, port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        # Create IE Driver instance of the unmanaged code
        self.iedriver = CDLL(
            os.path.join(os.path.dirname(__file__), "IEDriver.dll"))
        self.ptr = self.iedriver.StartServer(self.port)

        seconds = 0
        while not utils.is_connectable(self.port):
            seconds += 1
            if seconds > DEFAULT_TIMEOUT:
                raise RuntimeError("Unable to connect to IE")
            time.sleep(1)

        RemoteWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=DesiredCapabilities.INTERNETEXPLORER)
    def __init__(self, host, firefox_profile, firefox_binary=None, timeout=30):
        self.profile = firefox_profile
        self.binary = firefox_binary
        HOST = host
        timeout = int(timeout)

        if not self.binary:
            self.binary = FirefoxBinary()

        if not HOST:
            HOST = "127.0.0.1"

        PORT = utils.free_port()
        self.profile.port = PORT
        self.profile.update_preferences()

        self.profile.add_extension()

        self.binary.launch_browser(self.profile, timeout=timeout)
        _URL = "http://%s:%d/hub" % (HOST, PORT)
        super().__init__(_URL, keep_alive=True)
Exemple #46
0
    def __init__(self, executable_path='MicrosoftWebDriver.exe',
                 capabilities=None, port=0, verbose=False, service_log_path=None,
                 log_path=None, keep_alive=False):
        """
        Creates a new instance of the chrome driver.

        Starts the service and then creates new instance of chrome driver.

        :Args:
         - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
         - capabilities - Dictionary object with non-browser specific
           capabilities only, such as "proxy" or "loggingPref".
         - port - port you would like the service to run, if left as 0, a free port will be found.
         - verbose - whether to set verbose logging in the service
         - service_log_path - Where to log information from the driver.
         - log_path: Deprecated argument for service_log_path
         - keep_alive - Whether to configure ChromeRemoteConnection to use HTTP keep-alive.
         """
        if log_path:
            warnings.warn('use service_log_path instead of log_path',
                          DeprecationWarning, stacklevel=2)
            service_log_path = log_path

        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        self.edge_service = Service(executable_path, port=self.port, verbose=verbose, log_path=service_log_path)
        self.edge_service.start()

        if capabilities is None:
            capabilities = DesiredCapabilities.EDGE

        RemoteWebDriver.__init__(
            self,
            command_executor=RemoteConnection('http://localhost:%d' % self.port,
                                              resolve_ip=False,
                                              keep_alive=keep_alive),
            desired_capabilities=capabilities)
        self._is_remote = False
Exemple #47
0
    def __init__(self,
                 executable_path: str = DEFAULT_EXECUTABLE_PATH,
                 port: int = 0,
                 service_args: List[str] = None,
                 log_path: str = "geckodriver.log",
                 env: dict = None):
        """Creates a new instance of the GeckoDriver remote service proxy.

        GeckoDriver provides a HTTP interface speaking the W3C WebDriver
        protocol to Marionette.

        :param executable_path: Path to the GeckoDriver binary.
        :param port: Run the remote service on a specified port.
            Defaults to 0, which binds to a random open port of the
            system's choosing.
        :param service_args: Optional list of arguments to pass to the
            GeckoDriver binary.
        :param log_path: Optional path for the GeckoDriver to log to.
            Defaults to _geckodriver.log_ in the current working directory.
        :param env: Optional dictionary of output variables to expose
            in the services' environment.

        """
        log_file = open(log_path, "a+") if log_path else None

        service.Service.__init__(self,
                                 executable_path,
                                 port=port,
                                 log_file=log_file,
                                 env=env)
        self.service_args = service_args or []

        # Set a port for CDP
        if '--connect-existing' not in self.service_args:
            self.service_args.append("--websocket-port")
            self.service_args.append("%d" % utils.free_port())

        # Set the webdriver port
        self.service_args.append("--port")
        self.service_args.append("%d" % self.port)
def base_args(*port, **kwargs):
    if not port:  # 寻找空闲端口
        port = free_port()
    caps = get_caps()
    caps.update(getattr(Context, "ENV")["caps"])
    devices = Command().devices_and_version()
    n = 0
    if kwargs:
        for key, value in kwargs.items():
            caps[key] = value
    for res in devices:
        caps["deviceName"] = res[0]
        caps["platformVersion"] = res[1]
        service = AppiumService()
        service.start(
            args=["-a", "127.0.0.1", "-p", port[n], "--session-override"],
            timeout_ms=2000)
        driver = webdriver.Remote(
            command_executor='http://127.0.0.1:{}/wd/hub'.format(port[n]),
            desired_capabilities=caps)
        yield driver
        service.stop()
Exemple #49
0
 def start(cls):
     with open(rootPath + '/config/Ys.yaml', 'r', encoding='utf-8') as file:
         data = yaml.load(file)
         desired_caps = {}
         # desired_caps['app'] = rootPath+'/app/jc_print.apk'
         desired_caps['platformName'] = data['platformName']
         desired_caps['platformVersion'] = data['platformVersion']
         desired_caps['appPackage'] = data['appPackage']
         desired_caps['appActivity'] = data['appActivity']
         desired_caps['unicodeKeyboard'] = data['unicodeKeyboard']
         desired_caps['resetKeyboard'] = data['resetKeyboard']
         desired_caps['automationName'] = "uiautomator2"
         desired_caps['noReset'] = True
         desired_caps['systemPort'] = utils.free_port()
         udid = os.getenv('udid', None)
         if udid is not None:
             desired_caps['udid'] = udid
             print('udid is %s' % udid)
         cls.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',
                                       desired_caps)
         cls.driver.implicitly_wait(10)
     return MainPage(cls.driver)
Exemple #50
0
    def __init__(self, executable_path, port=0, quiet=False):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to the SafariDriver
         - port : Port the service is running on """

        if not os.path.exists(executable_path):
            if "Safari Technology Preview" in executable_path:
                message = "Safari Technology Preview does not seem to be installed. You can download it at https://developer.apple.com/safari/download/."
            else
                message = "SafariDriver was not found; are you running Safari 10 or later? You can download Safari at https://developer.apple.com/safari/download/."
            raise Exception(message)

        if port == 0:
            port = utils.free_port()

        self.quiet = quiet
        log = PIPE
        if quiet:
            log = open(os.devnull, 'w')
        service.Service.__init__(self, executable_path, port, log)
Exemple #51
0
    def __init__(self, executable_path=None, port=0, quiet=False, use_legacy=False):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to the SafariDriver
         - port : Port the service is running on """

        if not use_legacy and os.path.exists('/usr/bin/safaridriver'):
            path = '/usr/bin/safaridriver'
            self.legacy_driver = False
        else:
            path = 'java'
            self.standalone_jar = executable_path
            self.legacy_driver = True

        if port == 0:
            port = utils.free_port()

        self.quiet = quiet
        log = PIPE
        if quiet:
            log = open(os.devnull, 'w')
        service.Service.__init__(self, path, port, log)
Exemple #52
0
import time
import os
import subprocess

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common import utils

chrome_options = Options()
chrome_options.add_argument("nwapp=" + os.path.dirname(os.path.abspath(__file__)))
chrome_options.add_argument("mixed-context")

testdir = os.path.dirname(os.path.abspath(__file__))
os.chdir(testdir)

port = str(utils.free_port())
server = subprocess.Popen(['python', 'http-server.py', port])

tpl = open('index.tpl', 'r')
content = tpl.read().replace('{port}', port)
tpl.close()

html = open('index.html', 'w')
html.write(content)
html.close()

driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_options=chrome_options, service_log_path="log", service_args=["--verbose"])
try:
    print driver.current_url
    driver.implicitly_wait(10)
    driver.find_element_by_id('winopen').click()
Exemple #53
0
 def get_free_port(self):
     # We should really have a way to tell django to use a free port
     # provided by the OS but until then, we'll use the selenium trick. It's
     # racy but hopefully the OS doesn't reuse a port it just provided too
     # fast... -- vila 2013-07=05
     return utils.free_port()
    def __init__(self,
                 executable_path='IEDriverServer.exe',
                 capabilities=None,
                 port=DEFAULT_PORT,
                 timeout=DEFAULT_TIMEOUT,
                 host=DEFAULT_HOST,
                 log_level=DEFAULT_LOG_LEVEL,
                 service_log_path=DEFAULT_SERVICE_LOG_PATH,
                 options: Options = None,
                 service: Service = None,
                 desired_capabilities=None,
                 keep_alive=DEFAULT_KEEP_ALIVE):
        """
        Creates a new instance of the Ie driver.

        Starts the service and then creates new instance of Ie driver.

        :Args:
         - executable_path - Deprecated: path to the executable. If the default is used it assumes the executable is in the $PATH
         - capabilities - Deprecated: capabilities Dictionary object
         - port - Deprecated: port you would like the service to run, if left as 0, a free port will be found.
         - timeout - Deprecated: no longer used, kept for backward compatibility
         - host - Deprecated: IP address for the service
         - log_level - Deprecated: log level you would like the service to run.
         - service_log_path - Deprecated: target of logging of service, may be "stdout", "stderr" or file path.
         - options - IE Options instance, providing additional IE options
         - desired_capabilities - Deprecated: alias of capabilities; this will make the signature consistent with RemoteWebDriver.
         - keep_alive - Deprecated: Whether to configure RemoteConnection to use HTTP keep-alive.
        """
        if executable_path != 'IEDriverServer.exe':
            warnings.warn(
                'executable_path has been deprecated, please pass in a Service object',
                DeprecationWarning,
                stacklevel=2)
        if capabilities:
            warnings.warn(
                'capabilities has been deprecated, please pass in an Options object.'
                'This field will be ignored.',
                DeprecationWarning,
                stacklevel=2)
        if port != DEFAULT_PORT:
            warnings.warn(
                'port has been deprecated, please pass in a Service object',
                DeprecationWarning,
                stacklevel=2)
        if timeout != DEFAULT_TIMEOUT:
            warnings.warn(
                'timeout has been deprecated, please pass in a Service object',
                DeprecationWarning,
                stacklevel=2)
        if host != DEFAULT_HOST:
            warnings.warn(
                'host has been deprecated, please pass in a Service object',
                DeprecationWarning,
                stacklevel=2)
        if log_level != DEFAULT_LOG_LEVEL:
            warnings.warn(
                'log_level has been deprecated, please pass in a Service object',
                DeprecationWarning,
                stacklevel=2)
        if service_log_path != DEFAULT_SERVICE_LOG_PATH:
            warnings.warn(
                'service_log_path has been deprecated, please pass in a Service object',
                DeprecationWarning,
                stacklevel=2)
        if desired_capabilities:
            warnings.warn(
                'desired_capabilities has been deprecated, please pass in an Options object.'
                'This field will be ignored',
                DeprecationWarning,
                stacklevel=2)
        if keep_alive != DEFAULT_KEEP_ALIVE:
            warnings.warn(
                'keep_alive has been deprecated, please pass in a Service object',
                DeprecationWarning,
                stacklevel=2)
        else:
            keep_alive = True

        self.host = host
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()

        if not options:
            options = self.create_options()

        if service:
            self.iedriver = service
        else:
            self.iedriver = Service(executable_path,
                                    port=self.port,
                                    host=self.host,
                                    log_level=log_level,
                                    log_file=service_log_path)

        self.iedriver.start()

        RemoteWebDriver.__init__(self,
                                 command_executor=self.iedriver.service_url,
                                 options=options,
                                 keep_alive=keep_alive)
        self._is_remote = False
Exemple #55
0
    def __init__(self,
                 executable_path='IEDriverServer.exe',
                 capabilities=None,
                 port=DEFAULT_PORT,
                 timeout=DEFAULT_TIMEOUT,
                 host=DEFAULT_HOST,
                 log_level=DEFAULT_LOG_LEVEL,
                 service_log_path=DEFAULT_SERVICE_LOG_PATH,
                 options=None,
                 ie_options=None,
                 desired_capabilities=None,
                 log_file=None,
                 keep_alive=False):
        """
        Creates a new instance of the chrome driver.

        Starts the service and then creates new instance of chrome driver.

        :Args:
         - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
         - capabilities: capabilities Dictionary object
         - port - port you would like the service to run, if left as 0, a free port will be found.
         - timeout - no longer used, kept for backward compatibility
         - host - IP address for the service
         - log_level - log level you would like the service to run.
         - service_log_path - target of logging of service, may be "stdout", "stderr" or file path.
         - options - IE Options instance, providing additional IE options
         - ie_options - Deprecated argument for options
         - desired_capabilities - alias of capabilities; this will make the signature consistent with RemoteWebDriver.
         - log_file - Deprecated argument for service_log_path
         - keep_alive - Whether to configure RemoteConnection to use HTTP keep-alive.
        """
        if log_file:
            warnings.warn('use service_log_path instead of log_file',
                          DeprecationWarning,
                          stacklevel=2)
            service_log_path = log_file
        if ie_options:
            warnings.warn('use options instead of ie_options',
                          DeprecationWarning,
                          stacklevel=2)
            options = ie_options
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()
        self.host = host

        # If both capabilities and desired capabilities are set, ignore desired capabilities.
        if capabilities is None and desired_capabilities:
            capabilities = desired_capabilities

        if options is None:
            if capabilities is None:
                capabilities = self.create_options().to_capabilities()
        else:
            if capabilities is None:
                capabilities = options.to_capabilities()
            else:
                # desired_capabilities stays as passed in
                capabilities.update(options.to_capabilities())

        self.iedriver = Service(executable_path,
                                port=self.port,
                                host=self.host,
                                log_level=log_level,
                                log_file=service_log_path)

        self.iedriver.start()

        RemoteWebDriver.__init__(self,
                                 command_executor='http://localhost:%d' %
                                 self.port,
                                 desired_capabilities=capabilities,
                                 keep_alive=keep_alive)
        self._is_remote = False
Exemple #56
0
    def __init__(self,
                 executable_path='IEDriverServer.exe',
                 capabilities=None,
                 port=DEFAULT_PORT,
                 timeout=DEFAULT_TIMEOUT,
                 host=DEFAULT_HOST,
                 log_level=DEFAULT_LOG_LEVEL,
                 log_file=DEFAULT_LOG_FILE,
                 options=None,
                 ie_options=None,
                 desired_capabilities=None):
        """
        Creates a new instance of the chrome driver.

        Starts the service and then creates new instance of chrome driver.

        :Args:
         - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
         - capabilities: capabilities Dictionary object
         - port - port you would like the service to run, if left as 0, a free port will be found.
         - log_level - log level you would like the service to run.
         - log_file - log file you would like the service to log to.
         - options: IE Options instance, providing additional IE options
         - desired_capabilities: alias of capabilities; this will make the signature consistent with RemoteWebDriver.
        """
        if ie_options:
            warnings.warn('use options instead of ie_options',
                          DeprecationWarning)
            options = ie_options
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()
        self.host = host
        self.log_level = log_level
        self.log_file = log_file

        # If both capabilities and desired capabilities are set, ignore desired capabilities.
        if capabilities is None and desired_capabilities:
            capabilities = desired_capabilities

        if options is None:
            if capabilities is None:
                capabilities = self.create_options().to_capabilities()
        else:
            if capabilities is None:
                capabilities = options.to_capabilities()
            else:
                # desired_capabilities stays as passed in
                capabilities.update(options.to_capabilities())

        self.iedriver = Service(executable_path,
                                port=self.port,
                                host=self.host,
                                log_level=self.log_level,
                                log_file=self.log_file)

        self.iedriver.start()

        RemoteWebDriver.__init__(self,
                                 command_executor='http://localhost:%d' %
                                 self.port,
                                 desired_capabilities=capabilities)
        self._is_remote = False
 def test_should_fail_launching_tbb_tor_on_custom_socks_port(self):
     with self.assertRaises(TBDriverPortError):
         TorBrowserDriver(TBB_PATH,
                          socks_port=free_port(),
                          tor_cfg=cm.LAUNCH_NEW_TBB_TOR)
Exemple #58
0
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from nw_util import *

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common import utils

chrome_options = Options()
chrome_options.add_argument("nwapp=" +
                            os.path.dirname(os.path.abspath(__file__)))
chrome_options.add_experimental_option("windowTypes", ["webview"])

testdir = os.path.dirname(os.path.abspath(__file__))
os.chdir(testdir)

port_n = utils.free_port()
port = str(port_n)
server = subprocess.Popen(['python', '../http-server-node.py', port])

time.sleep(1)
tpl = open('index.tpl', 'r')
content = tpl.read().replace('{port}', port)
tpl.close()

html = open('index.html', 'w')
html.write(content)
html.close()

if not wait_net_service("127.0.0.1", port_n, 30):
    import platform
    if platform.system() == 'Windows':
Exemple #59
0
import os

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common import utils

chrome_options = Options()
chrome_options.add_argument("nwapp=" + os.path.dirname(os.path.abspath(__file__)))

driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_options=chrome_options)
driver.implicitly_wait(5)
time.sleep(1)
try:
    driver.implicitly_wait(10)
    print driver.current_url
    driver.execute_script('startServer(%s)' % utils.free_port())
    result = driver.find_element_by_id('server-started').get_attribute('innerHTML')
    print 'server started'
    driver.find_element_by_id('submit').click()
    result = driver.find_element_by_id('method').get_attribute('innerHTML')
    print result
    assert('POST' in result)
    driver.find_element_by_id('submit').click()
    result = driver.find_element_by_id('method').get_attribute('innerHTML')
    print result
    assert('POST' in result)
    result = driver.find_element_by_id('data').get_attribute('innerHTML')
    print result
    assert('myvalue2' in result)
finally:
    driver.quit()
Exemple #60
0
    '--proxy-type=https',
    '--load-images=false',
    '--ignore-ssl-errors=true',
    '--ssl-protocol=TLSv1',
    '--disk-cache=true',
]

MONGO_URL = 'localhost'
MONGO_DB = 'jd_apple'
MONGO_COLLECTION = 'mbp'
KEYWORD = 'Apple'

# 高版本selenium不再支持PhantomJS:Selenium support for PhantomJS has been deprecated, please use headless
driver = webdriver.PhantomJS(executable_path=EXECUTABLE_PATH,
                             service_args=SERVICE_ARGS,
                             port=free_port())
driver.set_window_size(1920, 1080)
page = WebDriverWait(driver, 10, 1)
client = MongoClient(MONGO_URL)
db = client[MONGO_DB]


# 搜索品牌,进入店铺,进入商品详情页,获取商品信息
def search_apple_goods():
    driver.get('https://www.jd.com/')
    try:
        print('搜索{}店铺'.format(KEYWORD))
        input_search = page.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, "#key")))
        btn_search = page.until(
            EC.element_to_be_clickable(