Linking selenium with electron framework (c#) - c#

I've already written few lines of code in C# using Selenium webdriver. As my application was transferred to the Electron framework everything has changed and honestly, I don't know how to cope with it right now.
Could you please clarify it to me? What steps should I take to simple start... I would like to continue my work in the current project (selenium, C#), but I'm not sure that it's possible, or I should completely start from scratch using a different language and framework?
I've read about Spectron, and checked the internet resources like stackoverflow, however I'm still in the point of unawareness...

Spectron with mocha is supposed to be faster.
But still here is what you need.This is Java & Selenium.
System.setProperty("webdriver.chrome.driver","C:\\electron-chromedriver\\bin\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary("C:\\Users\\app.exe");
chromeOptions.addArguments("start-maximized");
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability(CapabilityType.BROWSER_NAME, "Chrome");
capability.setCapability("chromeOptions", chromeOptions);
driver = new ChromeDriver(chromeOptions);
I have used the packaged electron app for binary (i.e) app.exe .
I think this is what you need.

Described below is related to using of Electron with .Net C# OpenQA.Selenium.
If you want to run electron app which being developed (consists of files index.html, main.js, etc.) you have to add following options (pay attention to 'app=' in cmd argument):
var options = new ChromeOptions();
options.BinaryLocation = #"your_path_to_electron\electron.exe";
options.AddArgument(#" app=path_to_folder_with_your_electron_app_src");
But if you want to run packaged electron app (*.exe) it is enough to use:
var options = new ChromeOptions();
options.BinaryLocation = #"path_to_folder_with_your_electron_app\your_electron_app.exe";
Also you can start any version of chromedriver.exe:
var service = ChromeDriverService.CreateDefaultService(path_to_folder_with_driver);
var driver = new ChromeDriver(service, options);
It might be helpful because I know that different electron applications are built on using of different version's drivers.

Try this for Electron application Initialization:
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
namespace Selenium_Demo
{
class Selenium_Demo
{
IWebDriver driver;
[SetUp]
public void Start_Browser()
{
ChromeOptions options = new ChromeOptions();
ChromeDriverService chromeService = ChromeDriverService.CreateDefaultService(#"C:\\selenium\\chromedriver_win32v\\chromedriver.exe",
#"C:\\Program Files\\Cerebrata\\Cerebrata.exe");
driver = new ChromeDriver(chromeService, options);
}
[Test]
public void Test()
{
System.Threading.Thread.Sleep(6000);
Console.WriteLine("Test Passed");
}
[TearDown]
public void Close_Browser()
{
driver.Quit();
}
}
}

Related

Avoid load images and other resources like css when use Selenium in c#

Good morning.
I am developing a spider to review a few web pages. I can't do it without using Selenium. But the problem with Selenium is that it consumes a lot of resources and is slow. I am looking for the optimization way.
From what I see the main problem is that Selenium loads the entire website, with all its resources. But I just need javascript and html to work for me. But I don't need images. Can I somehow prevent images from loading in the Selenium browser in C #?
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using (IWebDriver driver = SeleniumUtility.GetChromeDriverHidden())
{
driver.Url = "https://stackoverflow.com/";
string html = driver.PageSource;
}
internal static ChromeDriver GetChromeDriverHidden(bool hidden = true)
{
ChromeDriverService service = ChromeDriverService.CreateDefaultService(".");
service.HideCommandPromptWindow = true; // Hide output commands in console
var options = new ChromeOptions()
{
AcceptInsecureCertificates = true // This lets the browser accept the insecure certificate. Set hidden = false
};
if (hidden)
{
options.AddArgument("headless"); // hide window if added to options
}
return new ChromeDriver(service, options);
}
I see one solution, but in C# I don't understand how to do it.
Try this, I hope it helps
ChromeOptions options = new ChromeOptions();
options.addArguments("headless","--blink-settings=imagesEnabled=false");
Or
IWebDriver driver;
ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);
driver = new ChromeDriver(options);
See the original answer here

C# Selenium - headless browser

I develop a small app (in C#) which automatize a test on a website with Selenium. Everything is going well. But when I try the same app with "headless" browser the test doesn't work. I have an issue with the code below :
var emailTextBox = driver.FindElement(By.Id("j_username"));
OpenQA.Selenium.WebDriverException : 'The HTTP request to the remote WebDriver server for URL http://localhost:49309/session/d4416c4b-e674-468b-8d6e-6a8bfc9bdf1d/element timed out after 60 seconds.'
The same test works with a normal browser but not in headless mode, I try to use Firefox, Chrome, PhantomJS (all in headless) and it doesn't work...
Do you have an idea ?
My whole code is :
'''
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace MacDo
{
class Program
{
static void Main(string[] args)
{
var driverService = FirefoxDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
var options = new FirefoxOptions();
options.AddArguments("-headless");
IWebDriver driver = new FirefoxDriver(driverService, options);
driver.Url = "https://www.mcdonalds.fr/";
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10000);
System.Threading.Thread.Sleep(2000);
var seConnecter = driver.FindElement(By.Id("seconnecter"));
seConnecter.Click();
driver.Close();
driver.Quit();
Console.ReadKey();
}
}
}
'''
I use Firefox Browser 73.0.1 (32 bits) (-> I use Geckodriver version 0.26.0)
As said before, it works well, but not in headless mode...
I had the same issue in past where script did not work in headless and I found out it was due to default resolution. You can try adding
options.addArguments("window-size=1920,1080");
Worth trying!

If DesiredCapabilities are obsolute in Selenium 3+, what to use instead for mobile web tests?

I am trying to learn how to write automated web tests in SauceLabs, and Visual Studio is telling me that DesiredCapabilities is deprecated in Selenium 3. I figured out how to use ChromeOptions for desktop tests, but what about mobile web tests? This works:
DesiredCapabilities caps = new DesiredCapabilities();
caps.SetCapability("deviceName", "iPhone 8 Simulator");
caps.SetCapability("deviceOrientation", "portrait");
caps.SetCapability("platformVersion", "12.0");
caps.SetCapability("platformName", "iOS");
caps.SetCapability("browserName", "Safari");
caps.SetCapability("username", SauceUsername);
caps.SetCapability("accessKey", SauceAccessKey);
caps.SetCapability("name", TestContext.TestName);
_driver = new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"),
caps, TimeSpan.FromSeconds(600));
But I don't want to use a deprecated class. I've used Selenium exensively in the past, but this my first time doing mobile web tests (no apps, just Safari/mobile Chrome). Should I be using an Appium Driver instead?
There will be a AppiumOptions() in a future release of Appium v4 that will replace this. You can pull it down now and give it a try.
It will look something like this:
public void SimpleTest()
{
var appiumOptions = new AppiumOptions();
appiumOptions.AddAdditionalCapability(MobileCapabilityType.PlatformName, "Android");
appiumOptions.AddAdditionalCapability(MobileCapabilityType.PlatformVersion, "7.1.1");
appiumOptions.AddAdditionalCapability(MobileCapabilityType.FullReset, true);
appiumOptions.AddAdditionalCapability(MobileCapabilityType.NewCommandTimeout, 60);
appiumOptions.AddAdditionalCapability("testobject_api_key", "0D6C044F19D0442BA1E11C3FF087F6A6");
appiumOptions.AddAdditionalCapability("username", SauceUser.Name);
appiumOptions.AddAdditionalCapability("accessKey", SauceUser.AccessKey);
//TODO first you must upload an app to Test Object so that you get your app key
var rdcUrl = "https://us1.appium.testobject.com/wd/hub";
var driver = new AndroidDriver<IWebElement>(new Uri(rdcUrl), appiumOptions);
driver.Navigate().GoToUrl("https://www.ultimateqa.com");
Console.WriteLine("");
driver.Quit();
}
I think you should try this with appium driver. Just download appium c# client and start. You can use following link to start with.
http://appium.io/docs/en/writing-running-appium/web/mobile-web/

C# Selenium Start Chrome with Different User Profile

For the past 2 days, I've been trying to find a way to start Chrome with a different profile but to no avail.
No matter what I do, the profile that Selenium loads for chrome is always some temporary profile like "C:\Users\DARKBO~1\AppData\Local\Temp\scoped_dir14308_25046\Default"
I have tried the following code:
ChromeOptions options = new ChromeOptions();
options.AddArgument(#"user-data-dir=C:\SeleniumProfiles\Default");
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("chrome://version");
First I tried using the directories for the profiles directly from the Chrome folder, didn't work. Then I created a new folder and moved the profiles there, I've tried doing this both in C:\ and in D:\ . No difference whatsoever.
I've tried running the user-data-dir argument both like it currently is in the code and with -- in front of it. I've tried using double backslashes without the # symbol, still nothing. No matter what I do the profile directory is always the Selenium temp directory.
P.S. The current C:\SeleniumProfiles directory I created through the command prompt using the chrome user-data-dir=C:\SeleniumProfiles command
P.S. 2: My mistake was very simple, I forgot to put the options in the constructor of the new driver. And as Tarun made it clear, user-data-dir only gives Chrome the directory that contains the profiles, then we need to use profile-directory argument to give the subdirectory that contains the needed profile.
You din't use the options objects at all.
IWebDriver driver = new ChromeDriver();
Should be
IWebDriver driver = new ChromeDriver(options);
Edit-1 - Chrome profiles and users
Chrome has User data directory for storing profiles. Inside this directory multiple profiles can be maintained. There are two arguments that can be used
user-data-directory
profile-directory
If only user-data-directory is specified then a Default directory inside the same would be used. If profile-directory is specified then that directory inside the user-data-directory is used
If you are starting with the profile of the browser on the computer you are looking for, you can
Open normal google chrome and go to ('chrome://version')
enter link description here
Copy the Profile Path but take all of the "Data" folder and copy it to where the program is running
C# Coding:
https://rextester.com/INK23784
By creating a folder named "profile" where the program is running, you can add all the profile information, plugins, and so on. etc. We have copied the data folder in everything and when opening the browser "ChromeOptions" to selenium your profile files, etc. that's everything
You can try this code: (It worked for me)
string path_profile = #"D:\PROJECT_XMARKETING_4.0\Profiles\1";
// string path_profile = #"D:\PROJECT_XMARKETING_4.0\Profiles2\2";
IWebDriver _webDriver;
ChromeDriverService cService = ChromeDriverService.CreateDefaultService();
cService.HideCommandPromptWindow = true;
_webDriver = new ChromeDriver(cService);
_webDriver.Manage().Cookies.DeleteAllCookies();
ChromeOptions options = new ChromeOptions();
options.AddArgument($"user-data-dir={path_profile}");
_webDriver = new ChromeDriver(cService, options);
//_webDriver.Navigate().GoToUrl("https://phamtani.com/");
//_webDriver.Navigate().GoToUrl("https://alink.vn/");
//_webDriver.Navigate().GoToUrl("http://api.hostip.info/get_json.php");
Set user-data-dir to C:\Users[your-username]\AppData\Local\Google\Chrome\User Data
Full Code:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
private IWebDriver _driver { set; get; }
public YourConstructor()
{
_driver = CreateBrowserDriver();
}
private IWebDriver CreateBrowserDriver()
{
try
{
var options = new ChromeOptions();
options.AddArgument("test-type");
options.AddArgument("--ignore-certificate-errors");
options.AddArgument("no-sandbox");
options.AddArgument("disable-infobars");
//options.AddArgument("--headless"); //hide browser
options.AddArgument("--start-maximized");
//options.AddArgument("--window-size=1100,300");
//options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);
// Profile [Change:User name]
options.AddArgument(#"user-data-dir=C:\Users\Haddad\AppData\Local\Google\Chrome\User Data");
var service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
service.SuppressInitialDiagnosticInformation = true;
return new ChromeDriver(service, options);
}
catch
{
throw new Exception("Error: Chrome is not installed.");
}
}

ChromeOptions and DesiredCapabilities relations in Selenium and C#

I've been searching for the correct documentation on how to use ChromeOptions and DesiredCapabilities in the atmosphere of Selenium and C#, but since it's all open sourced, I only find suggestions (and they are not helping sometimes). My question today is how to setup the correct relation between ChromeOptions and DesiredCapabilities. Seems like I'm doing everything correctly, but still getting System.InvalidOperationException: unknown error:cannot parse capability: chromeOptions from unknown error: unrecognized chrome option:Arguments My code is following:
private static ChromeOptions Ops()
{
var options = new ChromeOptions();
options.AddArgument("--no-startup-window");
options.BinaryLocation = #"C:\path\path\path\chromedriver.exe";
return options;
}
private static DesiredCapabilities Caps()
{
DesiredCapabilities caps = new DesiredCapabilities();
caps.SetCapability(CapabilityType.BrowserName, "chrome");
caps.SetCapability(ChromeOptions.Capability,Ops().ToCapabilities());
return caps;
}
IWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), Caps());
Can't find a place where incorrect Arguments are passing. Has anybody faced the same issues? This is ChromeDriver version 2.28 and selenium WebDriver v 3.3.0 Google Chrome browser version is 52.
You don't need to set the browser name; ChromeOptions does that for you.
According to this comment
The .NET bindings are moving toward a pattern where DesiredCapabilites should not be
used directly, even with RemoteWebDriver. To facilitate that, the ChromeOptions class
has a ToCapabilities() method
And there's this comment
Much like --disable-javascript, the chromedriver will not work if you use --no-startup-window.
It needs to launch a window to establish the connection with the AutomationProxy.
So that gets us to this:
var options = new ChromeOptions();
options.BinaryLocation = #"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
IWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities());
However, are you actually running a grid? If you're testing on a single machine it's even simpler:
IWebDriver driver = new ChromeDriver();

Categories