I want to run multiple chrome instances with different profiles(each profile have their cookies) to do some task simultaneous . For example I want to search on Google with 2 accounts(each account have their proxy).
I use Visual Studio Community 2015.
This is what I do until now (without proxies):
namespace ChromeBot
{
class Program
{
public static object Application { get; private set; }
static void Main(string[] args)
{
//Set specific profile for Google Chrome
var options = new ChromeOptions();
options.AddArguments("user-data-dir=C:/Users/conta/AppData/Local/Google/Chrome/User Data/");
options.AddArguments("--start-maximized");
options.AddArguments("--profile-directory=Profile 1");
//Create the reference for our browser
IWebDriver driver = new ChromeDriver(options);
driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(0, 0, 0, 12));
//Navigate to Google Page
driver.Navigate().GoToUrl("http://www.google.com");
//Find the element
IWebElement element = driver.FindElement(By.Name("q"));
//Perform ops
element.SendKeys("cars");
// Set specific profile for Google Chrome1
var options1 = new ChromeOptions();
options1.AddArguments("user-data-dir=C:/Users/conta/AppData/Local/Google/Chrome/User Data/");
options1.AddArguments("--start-maximized");
options1.AddArguments("--profile-directory=Profile 2");
//Create the reference for our browser 1
IWebDriver driver1 = new ChromeDriver(options1);
driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(0, 0, 0, 12));
//Navigate to Google Page 1
driver1.Navigate().GoToUrl("http://www.google.com");
//Find the element
IWebElement element = driver.FindElement(By.Name("q"));
//Perform ops
element.SendKeys("smartphones");
}
}
}
When run this code open each profile and do nothing..
Any help?
When user launches chrome through chromedriver it opens a new instance of chrome browser and locks user-data-dir. hence if any other instance tries to open with same user-data-dir, the second instance do not responds.
Please launch each chrome instance with different user-data-dir.
Related
The problem is that I need to get the PID of IE browser instances so that I can close the IE browser(Working in C#).
I launched the IE browser using Selenium and then used Driver Service class as :-
InternetExplorerDriverService driverdetails = InternetExplorerDriverService.CreateDefaultService();
Console.WriteLine(driverdetails.Port);
The plan is to get the port and then have its child process. I am able to do so using a debugger by entering the value of Port manually. But, the port fetched by driverdetails.Port was not the actual port used by my driver.
Is there any was, I can find the Port for any given driver service?
For IE i have an alternative to launch IE and get the URL with port which says http://localhost:. However, this is not the case with other browsers. My want is to make the generic code and hence I am using the Driver Service object.
As far as I know, the InternetExplorerDriverService's ProcessID property gets the process ID of the running driver service executable, and we can't get the IE browser instance PID through the InternetExplorer webdriver. If you want to get the PID, you could try to use the Process class.
From your description, it seems that you want to close the IE tab or window by using the IE Webdriver. If that is the case, I suggest you could use InternetExplorerDriver WindowHandles to get the opened windows, then use the switchto method to switch the window and check the url or title, finally, call the Close method to close the IE window. Please refer to the following sample code:
private const string URL = #"https://dillion132.github.io/login.html";
private const string IE_DRIVER_PATH = #"D:\Downloads\webdriver\IEDriverServer_x64_3.14.0"; // where the Selenium IE webdriver EXE is.
static void Main(string[] args)
{
InternetExplorerOptions opts2 = new InternetExplorerOptions() { InitialBrowserUrl = "https://www.bing.com", IntroduceInstabilityByIgnoringProtectedModeSettings = true, IgnoreZoomLevel = true };
using (var driver = new InternetExplorerDriver(IE_DRIVER_PATH, opts2))
{
driver.Navigate();
Thread.Sleep(5000);
//execute javascript script
var element = driver.FindElementById("sb_form_q");
var script = "document.getElementById('sb_form_q').value = 'webdriver'; console.log('webdriver')";
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript(script, element);
InternetExplorerDriverService driverdetails = InternetExplorerDriverService.CreateDefaultService(IE_DRIVER_PATH);
Console.WriteLine(driverdetails.Port);
// open multiple IE windows using webdriver.
string url = "https://www.google.com/";
string javaScript = "window.open('" + url + "','_blank');";
IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)driver;
jsExecutor.ExecuteScript(javaScript);
Thread.Sleep(5000);
//get all opened windows (by using IE Webdriver )
var windowlist = driver.WindowHandles;
Console.WriteLine(windowlist.Count);
//loop through the list and switchto the window, and then check the url
if(windowlist.Count > 1)
{
foreach (var item in windowlist)
{
driver.SwitchTo().Window(item);
Console.WriteLine(driver.Url);
if(driver.Url.Contains("https://www.bing.com"))
{
driver.Close(); //use the Close method to close the window. The Quit method will close the browser window and dispose the webdriver.
}
}
}
Console.ReadKey();
}
Console.ReadKey();
}
So I've been trying to open IE in Private using selenium (C#), this is the closest i've come so far:
InternetExplorerOptions op = new InternetExplorerOptions();
op.PageLoadStrategy = PageLoadStrategy.Normal;
op.IgnoreZoomLevel = true;
op.InitialBrowserUrl = "https://entry.wgrintra.net/schadenwv/servlet/main";
op.ForceCreateProcessApi = true;
op.BrowserCommandLineArguments = "-private";
IWebDriver driver = new InternetExplorerDriver(op);
The problem here is, after 60 seconds of opening the browser (correctly in private) the driver times out (last step doesn't finish).
I've looked around a lot, most is just using Capabilities which are not useful anymore.
(I had to add a value to the registry to be able to forcecreate the process api)
Try to refer code example below and make a test with it on your side may help to solve your issue.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
* Created by Amol Chavan on 9/19/2016.
*/
public class PrivateBrowsing {
public static void main(String args[]){
createInstance();
}
public static WebDriver createInstance(){
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, true);
capabilities.setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");
System.setProperty("webdriver.ie.driver","C:\\Grid\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver(capabilities);
driver.get("http://www.google.com");
return driver;
}
}
Reference:
How to Open Internet Explorer Browser in Incognito / Private mode using Selenium / WebDriver ?
When using Chrome Selenium WebDriver, it will output diagnostic output when the servers are started:
Started ChromeDriver (v2.0) on port 9515
I do not want to see these messages, how can I suppress them?
I do this
ChromeOptions options = new ChromeOptions();
options.AddArgument("--silent");
IWebDriver Driver = new ChromeDriver(options);
But diagnostic output is not suppress.
I simply do this
ChromeOptions options = new ChromeOptions();
options.AddArgument("--log-level=3");
IWebDriver driver = new ChromeDriver(options);
Good question, however, I don't know where you got that .AddArgument("--silent"); thing, as that's Chrome's command line switch, not for ChromeDriver. Also, there isn't a Chrome switch called --silent anyway.
Under OpenQA.Selenium.Chrome namespace, there is class called ChromeDriverService which has a property SuppressInitialDiagnosticInformation defaults to false. Basically what you might want to do is to create
ChromeDriverService and pass it into ChromeDriver's constructor. Please refer to the documentation here.
Here is the C# code that suppresses ChromeDriver's diagnostics outputs.
ChromeOptions options = new ChromeOptions();
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.SuppressInitialDiagnosticInformation = true;
IWebDriver driver = new ChromeDriver(service, options);
EDIT:
ChromeDriver (not Chrome) has a command line argument --silent, which is supposed to work. SuppressInitialDiagnosticInformation in .NET binding does exactly that. However, it seems only suppress some of the messages.
Here is a closed chromedriver ticket:
Issue 116: How to disable the diagnostic messages and log file from Chrome Driver?
For me no one of previous answers did not help , my solution was:
ChromeDriverService service = ChromeDriverService.CreateDefaultService(driverLocation);
service.SuppressInitialDiagnosticInformation = true;
service.HideCommandPromptWindow = true;
var driver = new ChromeDriver(service, options);
For me the only thing that worked for
selenium-chrome-driver-2.48.2.jar
chromedriver 2.20
selenium-java-2.48.2.jar
was
ChromeOptions options = new ChromeOptions();
System.setProperty("webdriver.chrome.args", "--disable-logging");
System.setProperty("webdriver.chrome.silentOutput", "true");
driver = new ChromeDriver(options);
try this code it will hide browser with "headless" Argument but Chrome ver should > 58
( and even you can hide command prompt window )
IWebDriver driver;
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-extensions");
options.AddArgument("test-type");
options.AddArgument("--ignore-certificate-errors");
options.AddArgument("no-sandbox");
options.AddArgument("--headless");//hide browser
ChromeDriverService service = ChromeDriverService.CreateDefaultService(#"chromedriverExepath\");
service.SuppressInitialDiagnosticInformation = true;
//service.HideCommandPromptWindow = true;//even we can hide command prompt window (with un comment this line)
options.BinaryLocation = #"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
driver = new ChromeDriver(service, options);
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("https://www.example.com");
For anyone finding themselves here wanting a Java solution, there is a thread here:
Selenium chromedriver disable logging or redirect it java
To run Chrome browser with Selenium in console in completely silent mode, you should use this snippet:
options = Options()
options.headless = True
options.add_experimental_option("excludeSwitches", ["enable-logging"])
That trick will suppress any console message from either the Selenium driver or the browser itself, including the first message DevTools listening on ws://127.0.0.1 at the very start.
only add below line
System.setProperty("webdriver.chrome.silentOutput", "true");
output:-
ChromeDriver was started successfully.
Jun 28, 2022 10:38:55 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
This code works fine for me:
public static IWebDriver Driver { set; get; }
-----
Driver = CreateBrowserDriver();
////////////// Create Driver
private static IWebDriver CreateBrowserDriver()
{
try
{
var options = new OpenQA.Selenium.Chrome.ChromeOptions();
options.AddArguments("--disable-extensions");
options.AddArgument("--headless"); // HIDE Chrome Browser
var service = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true; // HIDE Chrome Driver
service.SuppressInitialDiagnosticInformation = true;
return new OpenQA.Selenium.Chrome.ChromeDriver(service, options);
}
catch
{
throw new Exception("Please install Google Chrome.");
}
}
////////////// Exit Driver
public static void ExitDriver()
{
if (Driver != null)
{
Driver.Quit();
}
Driver = null;
try
{
// Chrome
System.Diagnostics.Process.GetProcessesByName("chromedriver").ToList().ForEach(px => px.Kill());
}
catch { }
}
i am automating a process on firefox using selenium with c# .NET4.0:
static void Main(string[] args)
{
selenium = new DefaultSelenium("localhost", 4444, "*firefox", "https://www.microsoft.com/");
selenium.Start();
selenium.SetSpeed("900");
selenium.WindowMaximize();
selenium.WindowFocus();
Login();
}
public static void LogIn()
{
verificationErrors = new StringBuilder();
selenium.SetSpeed("900");
selenium.Open("/Login.aspx");
selenium.Type("id=ctl00_cphBody_objLogin_UserName", "user");
selenium.Type("id=ctl00_cphBody_objLogin_Password", "P#assword");
selenium.Click("id=ctl00_cphBody_objLogin_LoginImageButton");
selenium.WaitForPageToLoad("30000");
try
{
selenium.IsTextPresent("Orders - Drug Testing");
}
catch (Exception)
{
Console.WriteLine("Could't find text: Orders - Drug Testing.");
}
}
firefox opens, and then NOTHING happens at all. it does not navigate to the requested page.
here's what it looks like. what am i doing wrong? everything works fine with IE
To navigate to the requested page, need to use the following piece of code.
Selenium doesn't navigate to the page or base url automatically until & unless you call
selenium.open(" < your url goes here > ");
Ex : selenium.open("https://mail.google.com");
I am trying to use a profile I already have set up for firefox with selenium 2 but there is no documentation for C#. The code I have attempted is as follows:
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile(profileName);
driver = new FirefoxDriver(profile);
Code that I have seen that is comparible in Java uses ProfilesIni instead of FirefoxProfileManager, but that is not available in C#. When setting up the driver in this way the selenium profile used has all the default settings instead of the settings specified in the profile I am trying to point to.
I am not sure that I am using the correct methods to retrieve the profile, but if anyone has used Selenium 2 with C#, any information would be helpful.
We use such method to load default firefox profile (you can create custom profile and load it):
private IWebDriver driver;
string pathToCurrentUserProfiles = Environment.ExpandEnvironmentVariables("%APPDATA%") + #"\Mozilla\Firefox\Profiles"; // Path to profile
string[] pathsToProfiles = Directory.GetDirectories(pathToCurrentUserProfiles, "*.default", SearchOption.TopDirectoryOnly);
if (pathsToProfiles.Length != 0)
{
FirefoxProfile profile = new FirefoxProfile(pathsToProfiles[0]);
profile.SetPreference("browser.tabs.loadInBackground", false); // set preferences you need
driver = new FirefoxDriver(new FirefoxBinary(), profile, serverTimeout);
}
else
{
driver = new FirefoxDriver();
}
We had the same problem that the profile wouldn't load. The problem is in FirefoxProfile (line 137). It only looks for user.js and the profile from Firefox is actually prefs.js
137>> File prefsInModel = new File(model, "user.js");
Hack solution: rename prefs.js --> user.js
The following worked for me. I had to specifically set the "webdriver.firefox.profile" preference in order to get it to work.
var allProfiles = new FirefoxProfileManager();
if (!allProfiles.ExistingProfiles.Contains("SeleniumUser"))
{
throw new Exception("SeleniumUser firefox profile does not exist, please create it first.");
}
var profile = allProfiles.GetProfile("SeleniumUser");
profile.SetPreference("webdriver.firefox.profile", "SeleniumUser");
WebDriver = new FirefoxDriver(profile);
I have the same issue, it is not a duplicate.
I am using the following which works
private IWebDriver Driver;
[Setup]
public void SetupTest()
{
string path = #"C:\Users\username\AppData\Local\Mozilla\Firefox\Profiles\myi5go1k.default";
FirefoxProfile ffprofile = new FirefoxProfile(path);
Driver = new FirefoxDriver(ffprofile);
}
After using the aforementioned answers I had no result, so I tried the following alternate way:
First, create the desired profile by typing about:profiles on Firefox address bar.
Second, the C# code. Note that the profile name we created on first step is passed as an argument.
public IWebDriver driver { get; set; }
public Selenium(String nombrePefil)
{
if (this.driver == null)
{
FirefoxOptions options = new FirefoxOptions();
options.AddArgument("--profile " + nombrePefil);
this.driver = new FirefoxDriver(options);
}
}
I also encountered the same issue, and after searching and trying many different combinations I was able to get Selenium to load a specific profile when using the RemoteWebDriver.
Grid configuration
I launch the HUB using a batch file containing the following
"C:\Program Files (x86)\Java\jre6\bin\java.exe" -jar C:\Downloads\Selenium\selenium-server-standalone-2.20.0.jar -role hub -maxSession 50 -Dwebdriver.firefox.profile=Selenium
I launch one or more nodes using a batch file containing the following (each node has a unique port number):
"C:\Program Files (x86)\Java\jre6\bin\java.exe" -jar selenium-server-standalone-2.20.0.jar -role node -hub http://127.0.0.1:4444/grid/register -browser browserName=firefox,platform=WINDOWS,version=11.0,maxInstances=2 -maxSession 2 -port 5555 -Dwebdriver.firefox.profile=Selenium
The key here is the last part of those commands, which needs to match the name of the custom profile you have created.
Code to create WebDriver instance
private readonly Uri _remoteWebDriverDefaultUri = new Uri("http://localhost:4444/wd/hub/");
private IWebDriver CreateFireFoxWebDriver(Uri remoteWebDriverUri)
{
var desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.SetCapability(CapabilityType.BrowserName, "firefox");
desiredCapabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
desiredCapabilities.SetCapability(CapabilityType.Version, "11.0");
var drv = new RemoteWebDriver(remoteWebDriverUri ?? _remoteWebDriverDefaultUri, desiredCapabilities);
return drv;
}
NOTE: The capabilities need to match those of the nodes you are running in the grid.
You can then call this method passing in the Uri of the hub, or null to default to localhost.
Seems fine with the Roaming profile rather than the local profile.
string path = #"C:\Users\username\AppData\Roaming\Mozilla\Firefox\Profiles\myi5go1k.default";
FirefoxProfile ffprofile = new FirefoxProfile(path);
Driver = new FirefoxDriver(ffprofile);