Launching Selenium Hub, testing two browsers and executing tests using Selenium Python only on one of them

Summary: I have set up Selenium hub on my Mac and launched two browsers, but the test only runs in one. What could be causing this issue?

I recently installed Selenium hub on my Mac running OS X 10.11.5 using the instructions from this link. After installation, I launched the hub in a terminal tab with the following command:

selenium-standalone start -- -role hub

Next, in another terminal tab on the same machine, I registered a node as follows:

selenium-standalone start -- -role node -hub http://localhost:4444/grid/register -port 5556

Upon checking the console, I can see that there are 5 available Firefox and Chrome browsers.

In my Python file named globes.py, I have defined the desired capabilities for each browser like so:

class globes:
    def __init__(self, number):
        self.number = number

    base_url = "https://fake-example.com"

    desired_cap = []
    desired_cap.append ({'browserName':'chrome', 'javascriptEnabled':'true', 'version':'', 'platform':'ANY'})
    desired_cap.append ({'browserName':'firefox', 'javascriptEnabled':'true', 'version':'', 'platform':'ANY'})
    selenium_server_url = 'http://127.0.0.1:4444/wd/hub'

The test I am attempting to run looks like this:

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from globes import *

class HeroCarousel(unittest.TestCase):

    def setUp(self):
        for driver_instance in globes.desired_cap:
            self.driver = webdriver.Remote(
                command_executor=globes.selenium_server_url,
                desired_capabilities=driver_instance)

        self.verificationErrors = []

    def test_hero_carousel(self):
        driver = self.driver
        driver.get(globes.base_url)

        hero_carousel = driver.find_element(By.CSS_SELECTOR, 'div.carousel-featured')
        try: self.assertTrue(hero_carousel.is_displayed())
        except AssertionError, e: self.verificationErrors.append("home_test: Hero Carousel was not visible")

    def tearDown(self):
        self.driver.close()
        self.assertEqual([], self.verificationErrors)


if __name__ == "__main__":
    unittest.main()

Although both Firefox and Chrome browsers are launched, the test runs only in Firefox. Chrome does not execute the test and remains on a blank page without closing. I suspect there might be an issue with how I have structured the test. Can someone point out what I might be missing? I recently started learning Python specifically for writing Selenium tests, so any guidance would be appreciated.

I believe the hub is functioning correctly since it launches both browsers. I attempted adding a second node on a different port on the same machine, but encountered the same problem. Here's the output from the hub for reference:

INFO - Got a request to create a new session: Capabilities [{browserName=chrome, javascriptEnabled=true, version=, platform=ANY}]
INFO - Available nodes: [http://192.168.2.1:5557]
INFO - Trying to create a new session on node http://192.168.2.1:5557
INFO - Trying to create a new session on test slot {seleniumProtocol=WebDriver, browserName=chrome, maxInstances=5, platform=MAC}
INFO - Got a request to create a new session: Capabilities [{browserName=firefox, javascriptEnabled=true, version=, platform=ANY}]
INFO - Available nodes: [http://192.168.2.1:5557]
INFO - Trying to create a new session on node http://192.168.2.1:5557
INFO - Trying to create a new session on test slot {seleniumProtocol=WebDriver, browserName=firefox, maxInstances=5, platform=MAC}

Answer №1

Apologies if my response is not completely accurate, as I do not have experience working with selenium. However, the solution provided is based on addressing an issue related to maintaining a reference to the latest driver created in the setUp method.

Instead of just having one instance of self.driver, it is suggested to have a list named self.drivers to store all drivers. This way, you can loop through each driver by using for driver in self.drivers: and appropriately indent the relevant code within the loop. Here is an example:

class HeroCarousel(unittest.TestCase):

    def setUp(self):
        self.drivers = [] #this could also be done with list comprehension
        for driver_instance in globes.desired_cap:
            driver = webdriver.Remote(
                command_executor=globes.selenium_server_url,
                desired_capabilities=driver_instance)
            self.drivers.append(driver)

        self.verificationErrors = []

    def test_hero_carousel(self):
        for driver in self.drivers:
            driver.get(globes.base_url)

            hero_carousel = driver.find_element(By.CSS_SELECTOR, 'div.carousel-featured')
            try: self.assertTrue(hero_carousel.is_displayed())
            except AssertionError as e: self.verificationErrors.append("home_test: Hero Carousel was not visible")

    def tearDown(self):
        for driver in self.drivers:
            driver.close()
        self.assertEqual([], self.verificationErrors)

Answer №2

It is important to call self.driver.quit() because if you don't, the browser will not properly close and you may end up with multiple instances running simultaneously.

Failing to quit the browser can result in unnecessary expenses as additional browser instances consume resources.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choose a checkbox by targeting a specific column value with XPath

While automating the testing with Selenium, I encountered an issue related to selecting a checkbox in a table row. To resolve this problem, I turned to XPath for assistance. Specifically, I needed to choose the row based on the file name. Below is the rele ...

Retrieve the browser version through the use of the Selenium WebDriver

Is there a way to retrieve the browser version? >>> from selenium import webdriver >>> driver = webdriver.Chrome() >>> print(version) <-- Any suggestions on how to accomplish this? Chrome 92.0 ...

Why is the regex findall function returning a strange x00 value?

Using a regex pattern, I am able to create a list of all key-value pairs found within a line of text. re.compile("\((.*?),(.*?)\)") My key-pair syntax follows the specified regex pattern. For example: (hex, 0x123456) When testing this in an ...

Transform a string within a tuple into an individual string

I have searched extensively on various coding forums, but I haven't come across a satisfactory solution to this particular issue. Is there a way to transform the following into p = 'test2' from p = ('test2') specifically, how ...

Choose the element of interest using Selenium

Dealing with a Tricky Pop-up Input Field When faced with the challenge of interacting with a pop-up input field that is difficult to select using traditional CSS selectors or Xpath in one of my tests, I found solace in knowing that the pop-up box will hav ...

Experiencing a problem with cucumber and selenium wherein the driver consistently turns null in a straightforward test scenario

I am facing a challenge with my test automation framework. I have noticed that when directly finding elements inside the step definitions class, it works fine. However, when I try to implement a base class along with page object model and page factory, it ...

I am having trouble with base64 decoding and encoding in Python

This data is encoded in Base64 format: cg4AAAAAAAB7ACIAbQBTAGgAYQBkAG8AdwBGAG8AbgB0AE0AYQBwAEgAYQBzAGgAIgA6ACIAOQBjADkAOQBkAGYAMwAwAC0AOAA3AGUyAC0AMgBiNTMALQBkAGY5ADUALQBiN2VhZjAwADAAMAAwADAAMgAyAGQAIgAsACIAbQBUAGUAeAB0AFAAYQByAGEAbQAiADoAewAiAG0AQQBsAGkAZ ...

Python ModuleNotFound error when invoking Python code from system() function in R

I have a scenario where I have an R script running on my Raspberry Pi that calls a Python script using the system() function. Let's call this R script tweetsomething.R # first some data cleaning etc. system("python3 tweetImage.py var1 var2" ...

Error encountered while attempting to load token from file in the Discord.py event loop closing phase

As a precautionary measure, I've decided to keep my token in a separate file named token.txt. To load the token from the file and run the bot, I'm using the following code: f = open("token.txt", "r") token = f.readline() f.clo ...

Error: A CSV file must have at least one visible sheet to be read

I have a file in CSV format with the following structure: first-name,last-name,email-address Yes,Beth,<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="167473627e70776256717b777f7a3875797b">[email protected]</a> Ira ...

Error message states: "An error occurred while attempting to parse the json file

Currently enrolled in the Python Mega Course on Udemy, I'm diligently following the instructions to code all the recommended applications. However, while working on Application 2 - Creating Webmaps with Python and Folium, I encountered the following e ...

The JSONEncoder function is not getting invoked

My attempt to encode JSON using json.JSONEncoder with a different pattern by overriding the default method is not working as expected: class X(json.JSONEncoder): def default(self, obj): return ["ok"] json.dumps(self, cls=X) Despite following ...

"Resolve the issue with a stuck window in PySimpleGUI using Python

Recently, I attempted to develop a ChatGPT extension that opens a window, receives voice input, prints the response on the window, and uses text-to-speech to articulate it. However, during testing, while the program accepted input and generated responses, ...

Troubleshooting JSON compatibility problem in Django with Internet Explorer

Struggling with JSON compatibility issues in Internet Explorer (IE9). I've scoured the internet and tried various solutions to no avail. Decided it was time to create a Stack Overflow account and pose my first question. My JSON and jQuery/AJAX-based ...

What is the method for handling user input using Selenium WebDriver in Python?

I attempted to locate this input using selenium in order to test a login, but I have been unsuccessful in finding it. The code is written in python and I made several attempts as documented below: Most of the comments were notes on the different methods I ...

Displaying images in Dash Python by utilizing external Javascript

Dear audience, I am looking to incorporate an image on a Python Dash webpage that is created by JavaScript code. For more details, you can refer to the documentation here: . To include this script in a static HTML page, one would typically add the followi ...

Ordering results of Python script by location and grouping by shared identifier

There are numerous occurrences of data sharing the same location IDs, like in the output below where '3' is repeated multiple times: 121 {'data': {'id': 3, 'type': 'location'}, 'links': {&ap ...

Configuration Error: Pre-Test Setup Failed

An error message appeared stating that there was a failed connection to the binary FirefoxBinary located at C:\Program Files\Mozilla Firefox\firefox.exe on port 7055. The process output included various logs related to addons and blocklists. ...

What is the best way to tidy up messy JSON data filled with newline characters, extra spaces, and improper formatting using Python?

I'm currently working on a project where I am extracting data from pcpp in JSON format and my objective is to save this information into a file. from pcpartpicker import API import json api = API("in") categories = list(api.supported_parts) parts = ...

Is Selenium's Expected Conditions checking if an element is ready to be interacted with?

Does anyone know how to resolve the elementNotInteractable exception in selenium? I've tried using wait.until(ec.element_to_be_clickable()) However, my code still attempts to interact with elements that are not fully interactable. Could it be that I ...