Selenium Hub Launches 2 Browser Only Runs Test In 1 Of Them Selenium Python

Find the data you need here

We provide programming data of 20 most popular languages, hope to help you!

Previous PostNext Post

Selenium Hub, Launches 2 browser only runs test in 1 of them (selenium python)

selenium-standalone start -- -role hub
selenium-standalone start -- -role node -hub http://localhost:4444/grid/register -port 5556
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'
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()
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}
class HeroCarousel(unittest.TestCase):

    def setUp(self):
        self.drivers = [] #could make this 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, 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)

Using selenium web driver to run test on multiple browsers

There are already looooots of examples written. Share. Improve this answer. Follow answered Feb 28, 2012 at 13:09 Selenium Hub, Launches 2 browser only runs test in 1 of them (selenium python) Get HTML source of WebElement in Selenium WebDriver using Python. 1.

bros = ['FIREFOX','CHROME','INTERNET EXPLORER']

for bro in bros:
    print "Running "+bro+"\n"
    browser = webdriver.Remote(
                    command_executor='http://10.236.194.218:4444/wd/hub',
                    desired_capabilities={'browserName': bro,
                                          'javascriptEnabled': True})
    browser.implicitly_wait(60000)
    browser.get("http://10.236.194.156")
...
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
...

DesiredCapabilities[] browsers = {DesiredCapabilities.firefox(),DesiredCapabilities.chrome(),DesiredCapabilities.internetExplorer()};
    for(DesiredCapabilities browser : browsers)
    {
        try{
            System.out.println("Testing in Browser: "+browser.getBrowserName());
            driver = new RemoteWebDriver(new URL("http://127.0.0.1:4444/wd/hub"), browser);
            ...
@Parameters
public static List data() {
    return Arrays.asList(new Object[][]{{"firefox"},{"ie"}});
}
@Before
public void setUp() throws Exception {
    System.out.println("browser: " + browser);
    if(browser.equalsIgnoreCase("ie")) {
        System.setProperty("webdriver.ie.driver", "IEDriverServer64.exe");
        driver = new InternetExplorerDriver();
    } else if(browser.equalsIgnoreCase("firefox")) {
        driver = new FirefoxDriver();

Selenium 101: Running Your Test Against Two Browsers at Once

This means if you’re running a test in just two browsers at once, you’re already doubling your speed and productivity. When time is a factor to every software development team, parallel testing is a no-brainer. Selenium is able to run tests in parallel, but CrossBrowserTesting makes it even simpler - allowing you to test across multiple


browsers = [

browsers_waiting = [ ]

threads = []

Selenium - Multi Browser Testing

Selenium - Multi Browser Testing. Users can execute scripts in multiple browsers simultaneously. For demonstration, we will use the same scenario that we had taken for Selenium Grid. In the Selenium Grid example, we had executed the scripts remotely; here we will execute the scripts locally. First of all, ensure that you have appropriate


package TestNG;

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.testng.annotations.*;

public class TestNGClass {
   private WebDriver driver;
   private String URL = "http://www.calculator.net";

   @Parameters("browser")
   @BeforeTest
   public void launchapp(String browser) {

      if (browser.equalsIgnoreCase("firefox")) {
         System.out.println(" Executing on FireFox");
         driver = new FirefoxDriver();
         driver.get(URL);
         driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
         driver.manage().window().maximize();
      } else if (browser.equalsIgnoreCase("chrome")) {
         System.out.println(" Executing on CHROME");
         System.out.println("Executing on IE");
         System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
         driver = new ChromeDriver();
         driver.get(URL);
         driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
         driver.manage().window().maximize();
      } else if (browser.equalsIgnoreCase("ie")) {
         System.out.println("Executing on IE");
         System.setProperty("webdriver.ie.driver", "D:\\IEDriverServer.exe");
         driver = new InternetExplorerDriver();
         driver.get(URL);
         driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
         driver.manage().window().maximize();
      } else {
         throw new IllegalArgumentException("The Browser Type is Undefined");
      }
   }

   @Test
   public void calculatepercent() {
      // Click on Math Calculators
      driver.findElement(By.xpath(".//*[@id = 'menu']/div[3]/a")).click();

      // Click on Percent Calculators
      driver.findElement(By.xpath(".//*[@id = 'menu']/div[4]/div[3]/a")).click();

      // Enter value 10 in the first number of the percent Calculator
      driver.findElement(By.id("cpar1")).sendKeys("10");

      // Enter value 50 in the second number of the percent Calculator
      driver.findElement(By.id("cpar2")).sendKeys("50");

      // Click Calculate Button
      driver.findElement(By.xpath(".//*[@id = 'content']/table/tbody/tr/td[2]/input")).click();

      // Get the Result Text based on its xpath
      String result =
         driver.findElement(By.xpath(".//*[@id = 'content']/p[2]/span/font/b")).getText();		 

      // Print a Log In message to the screen
      System.out.println(" The Result is " + result);

      if(result.equals("5")) {
         System.out.println(" The Result is Pass");
      } else {
         System.out.println(" The Result is Fail");
      }
   }

   @AfterTest
   public void closeBrowser() {
      driver.close();
   }
}

Selenium Grid Tutorial: Hub & Node (with Example)

To install Selenium Grid, you only need to download the Selenium Server jar file – the same file used in running Selenium RC tests. There are 2 ways to verify if the hub is running: one was through the command prompt, and the other was through a browser; To run test scripts on the Grid, you should use the DesiredCapabilities and the

java -Dwebdriver.gecko.driver="C:\geckodriver.exe" -jar selenium-server-standalone-3.4.0.jar -role webdriver -hub http://192.168.1.3:4444/grid/register -port 5566
{
	  "port": 4444,
	  "newSessionWaitTimeout": -1,
	  "servlets" : [],
	  "withoutServlets": [],
	  "custom": {},
	  "capabilityMatcher": "org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
	  "registryClass": "org.openqa.grid.internal.DefaultGridRegistry",
	  "throwOnCapabilityNotPresent": true,
	  "cleanUpCycle": 5000,
	  "role": "hub",
	  "debug": false,
	  "browserTimeout": 0,
	  "timeout": 1800
}
java -jar selenium-server-standalone-2.53.1.jar -role hub -hubConfig hubconfig.json
http://192.168.43.223:4444/grid/console
Java-Dwebdriver.chrome.driver="chromedriver.exe" -Dwebdriver.ie.driver="IEDriverServer.exe" -Dwebdriver.gecko.driver="geckodriver.exe" -jar selenium-server-standalone-2.53.1.jar -role node -nodeConfig node1.json
 package com.objectrepository.demo;
 import org.openqa.selenium.*;
 import org.openqa.selenium.remote.DesiredCapabilities;
 import java.net.MalformedURLException;
 import java.net.URL;
 import org.openqa.selenium.remote.RemoteWebDriver;
 import org.testng.Assert;
 import org.testng.annotations.*;

 public class SeleniumGrid {

     WebDriver driver;
     String baseURL, nodeURL;

     @BeforeTest
     public void setUp() throws MalformedURLException {
         baseURL = "http://demo.guru99.com/test/guru99home/";
         nodeURL = "http://192.168.43.223:5566/wd/hub";
         DesiredCapabilities capability = DesiredCapabilities.chrome();
         capability.setBrowserName("chrome");
         capability.setPlatform(Platform.WIN10);
         driver = new RemoteWebDriver(new URL(nodeURL), capability);
     }

     @AfterTest
     public void afterTest() {
         driver.quit();
     }
     @Test
     public void sampleTest() {
         driver.get(baseURL);
         

         if (driver.getPageSource().contains("MOBILE TESTING")) {
             Assert.assertTrue(true, "Mobile Testing Link Found");
         } else {
             Assert.assertTrue(false, "Failed: Link not found");
         }

     }

 }

Selenium with Python Tutorial: Getting started with Test Automation

How to run your first Selenium tests with Python: Example. Once you have completed the pre-requisites section, you are ready to start your first test in Selenium with the Python programming language! 1. First import the WebDriver and Keys classes from Selenium. from selenium import webdriver from selenium.webdriver.common.keys import Keys

pip install selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome('./chromedriver')
driver.get("https://www.python.org")
print(driver.title)
Welcome to Python.org
search_bar = driver.find_element_by_name("q")
search_bar.clear()
search_bar.send_keys("getting started with python")
search_bar.send_keys(Keys.RETURN)
print(driver.current_url)
'https://www.python.org/search/?q=getting+started+with+python&submit='
driver.close()
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome('./chromedriver')
driver.get("https://www.python.org")
print(driver.title)
search_bar = driver.find_element_by_name("q")
search_bar.clear()
search_bar.send_keys("getting started with python")
search_bar.send_keys(Keys.RETURN)
print(driver.current_url)
driver.close()
<input id="id-search-field" name="q" type="search" role="textbox" class="search-field" placeholder="Search" value="" tabindex="1">
driver.switch_to_window('window_name')
print(driver.window_handles)
driver.switch_to_default_content()
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

try:
element = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.ID, "id-of-new-element"))
)
finally:
driver.quit()
driver.implicitly_wait(5)
element = driver.find_element_by_id("id-of-new-element")
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class ChromeSearch(unittest.TestCase):

def setUp(self):
self.driver = webdriver.Chrome('./chromedriver')

def test_search_in_python_org(self):
driver = self.driver
driver.get("https://www.python.org")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.send_keys("getting started with python")
elem.send_keys(Keys.RETURN)
assert "https://www.python.org/search/?q=getting+started+with+python&submit=" == driver.current_url

def tearDown(self):
self.driver.close()

if __name__ == "__main__":
unittest.main()
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

desired_cap = {
'browserName': 'android',
'device': 'Samsung Galaxy Note 9',
'realMobile': 'true',
'os_version': '8.1',
'name': 'Bstack-[Python] Sample Test'
}

driver = webdriver.Remote(
command_executor='https://<<user>>:<<user.keys>>@hub.browserstack.com:80/wd/hub',
desired_capabilities=desired_cap)

driver.get("https://www.google.com")
if not "Google" in driver.title:
raise Exception("Unable to load google page!")
elem = driver.find_element_by_name("q")
elem.send_keys("BrowserStack")
elem.submit()
print (driver.title)
driver.quit()
BrowserStack - Google Search

Execute Python Selenium tests in Selenium Grid

Before moving to python selenium test setup, let us understand what is selenium Grid and how to start it. which passes them to the node assigned to that test. The node runs the browser, and executes the Selenium commands within that browser against the application under test. You can start more than one nodes and register to same hub 2

$ java -jar selenium-server-standalone-3.11.0.jar -port 4444 -role hub
$ java -jar selenium-server-standalone-3.11.0.jar -host localhost -port 5555 -role node -hub http://localhost:4444/grid/register -browser browserName=firefox,platform=LINUX
from selenium import webdriver

desiredCapabilities={
"browserName":"chrome"
}

driver = webdriver.Remote(desired_capabilities = desiredCapabilities)
driver.get("https://www.google.co.in/")
print(driver.title)
driver.quit()
from selenium import webdriver

desiredCapabilities={
"browserName":"chrome"
}

driver = webdriver.Remote(command_executor='http://localhost:4444/wd/hub',desired_capabilities = desiredCapabilities)
driver.get("https://www.google.co.in/")
print(driver.title)
driver.quit()

How to do Multiple Browser Parallel Testing in a selenium TestNG project

Generate testng.xml. AS you can see I have name my Suite name “Suite1” and my Test name “Test1” Class selection: Here we can select what level we want to create our XML document. (class or

<dependency>    <groupId>org.seleniumhq.selenium</groupId>    <artifactId>selenium-java</artifactId>    <version>3.141.59</version></dependency>
<! —  https://mvnrepository.com/artifact/org.testng/testng →<dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.4.0</version> <scope>test</scope></dependency>
<dependency>    <groupId>io.github.bonigarcia</groupId>    <artifactId>webdrivermanager</artifactId>    <version>4.4.3</version></dependency>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"><suite name="Suite1">  <test thread-count="5" name="Test1">    <classes>      <class name="test.test"/>    </classes>  </test> <!-- Test1 --></suite> <!-- Suite1 -->
@Parameters("browserName")@BeforeTestpublic void setUp(String browserName){if(browserName.equalsIgnoreCase("chrome")) {  //initializing and starting the Chromebrowser  WebDriverManager.chromedriver().setup();  driver = new ChromeDriver(); }else if(browserName.equalsIgnoreCase("firefox")) {   //initializing and starting the Chromebrowser    WebDriverManager.firefoxdriver().setup();     driver = new FirefoxDriver();   }}
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"><suite name="Suite1" parallel="tests" thread-count="2">   <test name="test on firefox">  <parameter name="browserName" value="firefox"></parameter>    <classes>      <class name="test.test"/>    </classes>  </test> <!-- Test1 -->    <test name="test on chrome">  <parameter name="browserName" value="chrome"></parameter>    <classes>      <class name="test.test"/>    </classes>  </test> <!-- Test1 -->  </suite> <!-- Suite1 -->
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"><suite name="Suite1" parallel="tests" thread-count="2">   <test name="test on firefox">  <parameter name="browserName" value="firefox"></parameter>    <classes>      <class name="test.test"/>    </classes>  </test> <!-- Test1 -->    <test name="test on chrome">  <parameter name="browserName" value="chrome"></parameter>    <classes>      <class name="test.test"/>    </classes>  </test> <!-- Test1 -->     <test name="test2 on firefox">  <parameter name="browserName" value="firefox"></parameter>    <classes>      <class name="test.test"/>    </classes>  </test> <!-- Test1 --></suite> <!-- Suite1 -->
System.out.println("This test is on: " + Thread.currentThread().getId());
This test is on: 15This test is on: 16This test is on: 15
<class name="class_name" /><method>    <include name="MethodName"></include>    <exclude name="MethodName"></include></method>

Blank Browser launches on Selenium Grid Hub with Every Test Run on Node

Every time a test starts to run, a blank browser is launched on the hub before it opens the same type of browser on the node. After the test finishes this blank browser won't close either on the hub. How can I get it to stop opening the blank browser on each test or close the blank browser after each test on the hub? I have a driver.quit in

java -jar selenium-server-standalone-2.53.0.jar -role hub -hubConfig
Hub.json

java -jar selenium-server-standalone-2.53.0.jar -role node -nodeConfig 
WindowsNode.json

java -jar selenium-server-standalone-2.53.0.jar -role node -nodeConfig 
MacNode.json


Hub.JSON
{
"host": null,
"port": 4444,
"newSessionWaitTimeout": -1,
"servlets" : [],
"prioritizer": null,
"capabilityMatcher":
"org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
"throwOnCapabilityNotPresent": true,
"nodePolling": 5000,
"cleanUpCycle": 5000,
"timeout": 300000,
"browserTimeout": 0,
"maxSession": 1
}

WindowsNode.JSON
{
"capabilities":
[
    {
        "browserName": "firefox",
        "platform": "WINDOWS",
        "maxInstances": 1
    },
    {
        "browserName": "chrome",
        "platform": "WINDOWS",
        "maxInstances": 1,
        "webdriver.chrome.driver": "C:/Program Files (x86)/Google/Chrome
        /Application/chrome.exe" 
    },
    {
        "browserName": "internet explorer",
        "platform": "WINDOWS",
        "maxInstances": 1,
        "webdriver.ie.driver": "C:/Program Files (x86)/Internet 
        Explorer/iexplore.exe"      
    }
],
"configuration":
{
    "maxSession":1,
    "port":5554,
    "hubPort":4444,
    "hubHost": xxx.xxx.x.xx,
    "nodePolling":2000,
    "registerCycle":10000,
    "cleanUpCycle":2000,
    "timeout":30000,
    "Dwebdriver.chrome.driver=C:\\SeleniumStandaloneServer
    \\chromedriver.exe": "",
    "Dwebdriver.ie.driver=C:\\SeleniumStandaloneServer
    \\IEDriverServer.exe": ""
}
}


MACNode.JSON
{
"capabilities":
[
    {
        "browserName": "firefox",
        "platform": "MAC",
        "maxInstances": 1
    },
    {
        "browserName": "chrome",
        "platform": "MAC",
        "maxInstances": 1
    },
    {
        "browserName": "safari",
        "platform": "MAC",
        "maxInstances": 1
    }
],
"configuration":
{
"maxSession": 1,
"port": 5555,
"host": localhost,
"register": true,
"registerCycle": 5000,
"hubPort": 4444,
"hubHost": xxx.xxx.x.xx
}
}

<suite name="Suite" preserve-order="true" verbose="4" thread-count="2">

<test name="Tests1">    
    <parameter name="browser" value="internet explorer"/>
    <classes>
        <class name="Tests.A_Test"/>
    </classes>
</test> 

<test name="Tests2">    
    <parameter name="browser" value="chrome"/>
    <classes>
        <class name="Tests.A_Test"/>
    </classes>
</test> 


<test name="Tests3">    
    <parameter name="browser" value="firefox"/>
    <classes>
        <class name="Tests.A_Test"/>
    </classes>
</test> 

<test name="Tests4">    
    <parameter name="browser" value="safari"/>
    <classes>
        <class name="Tests.A_Test"/>
    </classes>
</test> 
</suite>

 public class TestBase {

    public static WebDriver driver=null;
    public String URL, Node;

    @BeforeTest
    @Parameters("browser")
    public void Setup (String browser) throws IOException, 
    MalformedURLException{
    {
        DesiredCapabilities capabilities = null;
        URL = "http://www.google.com";

        if(browser.equals("firefox"))
        {
            driver=new FirefoxDriver();
            capabilities = DesiredCapabilities.firefox();
            capabilities.setBrowserName("firefox");
            capabilities.setPlatform(Platform.ANY);
            Node = "http://xxx.xxx.x.xx:5554/wd/hub";
        }
        else if (browser.equals("chrome"))
        {
            //Start chromedriver in windows hub and on mac node
            System.setProperty("webdriver.chrome.driver", 
            "C:\\SeleniumStandaloneServer\\chromedriver.exe");
            driver=new ChromeDriver();
            capabilities = DesiredCapabilities.chrome();
            capabilities.setBrowserName("chrome");
            capabilities.setPlatform(Platform.ANY); 
            Node = "http://xxx.xxx.x.xx:5554/wd/hub";
        }
        else if (browser.equals("safari"))
        {
            driver = new SafariDriver();
            capabilities = DesiredCapabilities.safari();
            capabilities.setBrowserName("safari");
            capabilities.setPlatform(Platform.MAC);
            Node = "http://xxx.xxx.x.xx:5555/wd/hub";
        }
        else
        {

      System.setProperty("webdriver.ie.driver",
      "C:\\SeleniumStandaloneServer\\IEDriverServer.exe");
            driver=new InternetExplorerDriver();
            capabilities = DesiredCapabilities.internetExplorer();
            capabilities.setBrowserName("internet explorer");
            capabilities.setPlatform(Platform.WINDOWS);
            //Enable IE security tab protected mode for all zones 
            then you can skip flakiness line
          //capabilities.setCapability(InternetExplorerDriver.
          INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
            capabilities.setCapability("ensureCleanSession", true);
            capabilities.setCapability("ignoreZoomSetting", true);
            capabilities.setCapability("ignoreProtectedModeSettings", true);
            capabilities.setCapability("ignore-certificate-error", true);
            capabilities.setCapability("capabilityType.ACCEPT_SSL_CERTS", 
            true);
            Node = "http://xxx.xxx.x.xx:5554/wd/hub";
        }


        driver = new RemoteWebDriver(new URL(Node), capabilities);
        driver.get(URL);
        driver.manage().window().maximize(); 

    }       
}   


}

 public class A_Test extends TestBase {
 ...
 }

Previous PostNext Post

Related code examples