How to Launch Safari Browser in Selenium

Profile picture for user devraj

To launch a safari browser using selenium you don't need to download driver like chrome or Firefox; instead of driver you have to enable few settings on Safari Browser.

Step 1: Go to Safari -> Preferences

preferences in safari

Step 2: From Advanced section, Select checkbox Show Develop Menu in menu bar

enable developer menu in mac safari browser

Step 3: From Develop Menu Select Allow Remote Automation

allow remote automation in mac safari browser

 

Step 4: Add following code to intialize and launch website using Safari Driver.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.annotations.Test;

public class SafariBrowser 
{
    WebDriver driver;
		
    @Test
    public void MyMethod()
    {
        driver = new SafariDriver();
        driver.get("https://www.programsbuzz.com");	
        driver.manage().window().maximize();
        driver.quit();
    }
}

In above code,

  • WebDriver makes direct calls to the browser using each browser’s native support for automation. It uses browser driver for this communication.
  • new SafariDriver(), Here we are creating instance of SafariDriver to launch Safari Browser.
  • driver.get() is used to navigate particular URL of Website.

Safari Could not start a new session

If you are getting below error during execution. Make sure Safari is closed properly.

Could not start a new session. Response code 500. Message: Could not create a session: The Safari instance is already paired with another WebDriver session

To close safari manually go to Safari -> Quit Safari

Safari Could not start a new session