Cant Launch a window with Selenium Chrome Driver c# - c#

Environment:
Vs2019, C#
NuGet Package: Selenium v3.141.0 by Selenium Committee.
Chrome Driver from Selenium website - v92.0
IWebDriver Driver = new ChromeDriver("FolderPath"); //time out error here.
Driver.url = "www.google.com"
with no other code, I can't get pass declaring Chrome Driver. I get a time out error with local host.
I tried:
setting a different port.
adding "no-sandbox" to arguments.

I would try utilizing the ChromeDriver NuGet package instead of pointing to a local file location
https://www.nuget.org/packages/Selenium.WebDriver.ChromeDriver/
Here is a simple example for you to reference
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace ExampleDemo
{
[TestFixture]
public class Chrome_test
{
private IWebDriver driver;
[Test(Description="Go To Google")]
public void GoToGoogle() {
homeURL = https://www.google.com/;
driver.Navigate().GoToUrl(homeURL);
}
[TearDown]
public void TearDownTest()
{
driver.Close();
}
[SetUp]
public void SetupTest()
{
driver = new ChromeDriver();
}
}
}

I need to add a chrome option:
ChromeOptions options = new ChromeOptions()
options.add("--remote-debugging-port=9222 ") // change port if necessary

Related

How can I integrate selenium tests with sauce labs in c#?

On saucelabs website they provide a code snippet like this:
WebDriver webDriver = new WebDriver();
webDriver.set(new RemoteWebDriver(
new URL("https://UrlHEREagwgwgqwg4894+4+91gwgq")
))
When I add this to my tests, under WebDriver it says type or namespace 'WebDriver' could not be found. It is coming up for a namespace. For my Selenium tests I am using IWebDriver. I tried to change the WebDriver to IWebDriver and that didn't work. I also get the same error under the URL saying the namespace could not be found. For that one it does show for a namespace using System.Security.Policy; If I add that then I get an error under
new URL("https://UrlHEREagwgwgqwg4894+4+91gwgq")
Argument 1: cannot convert from 'System.Security.Policy.Url' to 'OpenQA.Selenium.DriverOptions'
This is how I am trying to use it. I was using ChromeDriver for my selenium tests but commented that part out to test on other browsers with saucelabs. This is my first time working with selenium/saucelabs so what I am doing my be completely off and I appreciate any advice.
[Fact]
public static void ClickDownloadButton()
{
WebDriver driver = new WebDriver();
driver.set(new RemoteWebDriver(
new Url("https://UrlHEREagwgwgqwg4894+4+91gwgq")
));
//using IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl(BaseUrl.downloadsUrl);
var login = new Login(driver);
login.EnterEmail();
login.EnterPassword();
login.HitSubmit();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
var downloadButton = wait.Until((d) => d.FindElements(By.LinkText("Download File")));
foreach (var button in downloadButton)
{
IWebElement element = wait.Until((d) => d.FindElement(By.LinkText("Download File")));
element.Click();
}
driver.Quit();
}
Here are the using statements:
using Xunit;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.IO;
using System.Security.Policy;
using OpenQA.Selenium.Remote;
Check out our demo C# repository with tons of examples.
Here's a working example that you can use from the following file:
using System;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;
namespace Selenium3.Nunit.Scripts.SimpleExamples
{
[TestFixture]
[Category("SimpleTest")]
public class SimpleSauceTest
{
IWebDriver _driver;
[Test]
public void SimpleTest()
{
//TODO please supply your Sauce Labs user name in an environment variable
var sauceUserName = Environment.GetEnvironmentVariable(
"SAUCE_USERNAME", EnvironmentVariableTarget.User);
//TODO please supply your own Sauce Labs access Key in an environment variable
var sauceAccessKey = Environment.GetEnvironmentVariable(
"SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);
ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability(CapabilityType.Version, "latest", true);
options.AddAdditionalCapability(CapabilityType.Platform, "Windows 10", true);
options.AddAdditionalCapability("username", sauceUserName, true);
options.AddAdditionalCapability("accessKey", sauceAccessKey, true);
options.AddAdditionalCapability("name", TestContext.CurrentContext.Test.Name, true);
options.AddAdditionalCapability("build", "ShwabTeamName:" + DateTime.Now, true);
_driver = new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"), options.ToCapabilities(),
TimeSpan.FromSeconds(600));
_driver.Navigate().GoToUrl("https://www.google.com");
Assert.Pass();
}
[TearDown]
public void CleanUpAfterEveryTestMethod()
{
var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
((IJavaScriptExecutor)_driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
_driver?.Quit();
}
}
}
Don't forget to install the correct Nuget packages so you have the corresponding resources. This is the minimum that you'll need:
<package id="Selenium.Support" />
<package id="Selenium.WebDriver" />
Side Note:
Don't use static methods as it'll make it impossible for you to parallelize.

Run Selenium Grid C# Project in Visual Studio

I'm implemented Nunit selenium C# testing in visual studio (Console Application n Class Library). My project in visual studio is console application. I started the selenium grid using
java -Dwebdriver.gecko.driver="..\jar\geckodriver.exe" -Dwebdriver.chrome.driver="..\jar\chromedriver.exe" -Dwebdriver.ie.driver="..\jar\IEDriverServer.exe" -jar ..\jar\selenium-server-standalone-3.14.0.jar -role hub -port 4444
Code:
using Automation_Framework.Manager;
using NUnit.Framework;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Text;
namespace Automation_Framework.TestManager
{
[TestFixture]
class ChromeTestManager
{
private WebDriverManager webDriverManager;
private IWebDriver driver;
public ChromeTestManager()
{
webDriverManager = new WebDriverManager();
}
[SetUp]
public void setup()
{
webDriverManager.createDriver("chrome");
driver = webDriverManager.getDriver();
}
[Test]
public void test()
{
driver.Url = "http://www.google.com.my";
driver.Navigate();
}
[TearDown]
public void shutdown()
{
driver.Close();
}
}
}
I had tried execute using Test Explorer but it does not open any browser. I"m following this tutorial.
Questions:
How to run the project with browser open and see all actions?
How to run using Nunit-console-runner.
Please help me. Thanks.
I assume that:
1. You have tried your code locally and your test is opening the browser when you run it on your machine without the grid.
2. Your nodes are set up and registered with the hub.
You need to:
1. Use RemoteWebDriver:
var uri = 'uri_to_your_grid_hub';
var capabilities = new ChromeOptions().ToCapabilities();
var commandTimeout = TimeSpan.FromMinutes(5);
var driver = new RemoteWebDriver(new Uri(uri),capabilities,commandTimeout)
Add the attribute to a class: [Parallelizable(ParallelScope.Self)] in order to run your tests in parallel with other test classes.
In order to verify whether the hub is running, open the browser and navigate to http://localhost:4444 on the hub machine.
Sources:
How can I run NUnit(Selenium Grid) tests in parallel?
Selenium Grid in C#
Useful C# WebDriver examples
Selenium Grid set up
I haven't used grid in .Net but here my answer:
your command is just register a hub, which needs to keep running (open a browser and test it is working)
you need to register your nodes under that hub (different ports) (open a browser and test it is working)
in your code, you should use "RemoteWebDriver" to connect to the hub.
something along these lines (it is in java but I hope it gives you a starting point)
public class Gmail
{
public WebDriver driver=null;
#Parameters("browser") //testng.xml
#Test()
public void GmailTest(String browser)
{
System.out.println("Gmail " + browser);
// RemoteWebdriver
DesiredCapabilities cap = null;
if(browser.equals("firefox")){
cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
cap.setPlatform(Platform.ANY);
}else if (browser.equals("iexplore")){
cap = DesiredCapabilities.internetExplorer();
cap.setBrowserName("iexplore");
cap.setPlatform(Platform.WINDOWS);
}
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),cap);
driver.get("http://gmail.com");
driver.findElement(By.id("Email")).sendKeys("abcd");
driver.quit();
}
I hope this helps.good luck

Building a selenium chrome webdriver with parameters and passing it to other methods in C#

I am new to Visual Studio 2015 and C#, my last coding exposure was about 15 years ago in a high school visual basic class. I have been asked to create a desktop application for someone else that goes to a webpage and performs some tasks. They want to click a couple buttons in the application instead of going to the page and don't want to see the browser or a command prompt.
I chose Selenium and C# in Visual Studio 2015 ent because it works with my needs for headlessly opening a chrome browser without the command prompt, also for office integration later. I did it like this:
//Sets up chrome webdriver with hidden console and headless mode.
ChromeOptions option = new ChromeOptions();
option.AddArguments("--headless");
var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
//Add "option" in ChromeDriver() to activate headless chrome \/
IWebDriver driver = new ChromeDriver(driverService);
"option" left out of ChromeDriver() for testing, I need to see what the browser is doing at this step.
And it works, but it was created in a button_click event. My problem now is that I don't know the correct way to establish the driver with all the parameters needed outside of this method. I'd also like to use that same driver's session again without starting over.
My end goal is to have that button populate the form with the contents of a CheckedListBox (the only part of the page that changes and needs direct input) then another button sending the user's selection to the page and generating a report.
Here is the relevant part:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace Report_Tool
{
public partial class ReportToolUI : Form
{
//Sets the chrome webdriver.
public static IWebDriver Driver { get; set; }
public ReportToolUI()
{
InitializeComponent();
}
public void ReportToolUI_Load(object sender, EventArgs e)
{
}
public void getListButton_Click(object sender, EventArgs e)
{
//Sets up chrome webdriver with hidden console and headless mode.
ChromeOptions option = new ChromeOptions();
option.AddArguments("--headless");
var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
//Add "option" in ChromeDriver() to activate headless chrome \/
IWebDriver driver = new ChromeDriver(driverService);
//Goes to obfuscated site.
driver.Navigate().GoToUrl("obfuscated");
}}}
What would be the correct way to create that webdriver once and call it in the different button_click methods?
Use a singleton:
public class Utils
{
private static IWebDriver _driver;
public static IWebDriver Driver {
get {
if (_driver == null) {
var service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
var options = new ChromeOptions();
options.AddArguments("--headless");
var commandTimeout = TimeSpan.FromSeconds(30);
_driver = new ChromeDriver(service, options, commandTimeout);
}
return _driver;
}
}
}
Then access the driver anywhere with Utils.Driver.

Appium C# AppiumDriver<AppiumWebElement>.DeviceTime does not work

How to get current time on real device (android) using selenium C#
I have tried AppiumDriver.DeviceTime
I got error:
Message: OpenQA.Selenium.WebDriverException : Unexpected error. That URL did not map to a valid JSONWP resource
I'm using Visual Studio Community 2017
//C# Appium getting time
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
namespace YourNameSpace
{
[TestClass]
public class UnitTest1
{
//Creating instance for Appium driver
AppiumDriver<AndroidElement> _driver;
[TestMethod]
public void MainScreen()
{
//set the capabilities
(https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/caps.md)
DesiredCapabilities cap = new DesiredCapabilities();
//remember to put here all your DesiredCapabilities
_driver = new AndroidDriver<AndroidElement>(new Uri("http://127.0.0.1:4723/wd/hub"), cap);
String deviceDateX = _driver.DeviceTime; //Geting device date and time.
Console.WriteLine(deviceDateX); //Writing the date and time in console
_driver.Quit();
}
}
}
I Hope this helps you. :)

How do I use Selenium in C#?

Selenium.
I downloaded the C# client drivers and the IDE. I managed to record some tests and successfully ran them from the IDE. But now I want to do that using C#. I added all relevant DLL files (Firefox) to the project, but I don't have the Selenium class. Some Hello, World! would be nice.
From the Selenium Documentation:
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
class GoogleSuggest
{
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
//Notice navigation is slightly different than the Java version
//This is because 'get' is a keyword in C#
driver.Navigate().GoToUrl("http://www.google.com/");
IWebElement query = driver.FindElement(By.Name("q"));
query.SendKeys("Cheese");
System.Console.WriteLine("Page title is: " + driver.Title);
driver.Quit();
}
}
Install the NuGet packet manager
Download link: https://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c
Create a C# console application
Right-click on the project → Manage NuGet Packages.
Search for "Selenium" and install package Selenium.Support.
You are done now, and you are ready to write your code :)
For code with Internet Explorer, download the Internet Explorer driver.
Link: http://selenium-release.storage.googleapis.com/index.html
Open 2.45 as its the latest release
Download IEDriverServer_x64_2.45.0.zip or IEDriverServer_Win32_2.45.0.zip
Extract and simply paste the .exe file at any location, for example C:\
Remember the path for further use.
Overall reference link: Selenium 2.0 WebDriver with Visual Studio, C#, & IE – Getting Started
My sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.IE;
namespace Selenium_HelloWorld
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new InternetExplorerDriver("C:\\");
driver.Navigate().GoToUrl("http://108.178.174.137");
driver.Manage().Window.Maximize();
driver.FindElement(By.Id("inputName")).SendKeys("apatra");
driver.FindElement(By.Id("inputPassword")).SendKeys("asd");
driver.FindElement(By.Name("DoLogin")).Click();
string output = driver.FindElement( By.XPath(".//*[#id='tab-general']/div/div[2]/div[1]/div[2]/div/strong")).Text;
if (output != null )
{
Console.WriteLine("Test Passed :) ");
}
else
{
Console.WriteLine("Test Failed");
}
}
}
}
To set up the IDE for Selenium in conjunction with C# is to use Visual Studio Express. And you can use NUnit as the testing framework. The below links provide you more details. It seems you have set up what is explained in the first link. So check the second link for more details on how to create a basic script.
How to setup C#, NUnit and Selenium client drivers on Visual Studio Express for Automated tests
Creating a basic Selenium web driver test case using NUnit and C#
Sample code from the above blog post:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
// Step a
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Firefox;
using NUnit.Framework;
namespace NUnitSelenium
{
[TestFixture]
public class UnitTest1
{
[SetUp]
public void SetupTest()
{
}
[Test]
public void Test_OpeningHomePage()
{
// Step b - Initiating webdriver
IWebDriver driver = new FirefoxDriver();
// Step c: Making driver to navigate
driver.Navigate().GoToUrl("http://docs.seleniumhq.org/");
// Step d
IWebElement myLink = driver.FindElement(By.LinkText("Download"));
myLink.Click();
// Step e
driver.Quit();
)
}
}
One of the things that I had a hard time finding was how to use PageFactory in C#. Especially for multiple IWebElements. If you wish to use PageFactory, here are a few examples. Source: PageFactory.cs
To declare an HTML WebElement, use this inside the class file.
private const string _ID ="CommonIdinHTML";
[FindsBy(How = How.Id, Using = _ID)]
private IList<IWebElement> _MultipleResultsByID;
private const string _ID2 ="IdOfElement";
[FindsBy(How = How.Id, Using = _ID2)]
private IWebElement _ResultById;
Don't forget to instantiate the page object elements inside the constructor.
public MyClass(){
PageFactory.InitElements(driver, this);
}
Now you can access that element in any of your files or methods. Also, we can take relative paths from those elements if we ever wish to. I prefer pagefactory because:
I don't ever need to call the driver directly using driver.FindElement(By.Id("id"))
The objects are lazy initialized
I use this to write my own wait-for-elements methods, WebElements wrappers to access only what I need to expose to the test scripts, and helps keeps things clean.
This makes life a lot easier if you have dynamic (autogerated) webelements like lists of data. You simply create a wrapper that will take the IWebElements and add methods to find the element you are looking for.
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(#"D:\DownloadeSampleCode\WordpressAutomation\WordpressAutomation\Selenium", "geckodriver.exe");
service.Port = 64444;
service.FirefoxBinaryPath = #"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
Instance = new FirefoxDriver(service);
C#
First of all, download Selenium IDE for Firefox from the Selenium IDE.
Use and play around with it, test a scenario, record the steps, and then export it as a C# or Java project as per your requirement.
The code file contains code something like:
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
// Add this name space to access WebDriverWait
using OpenQA.Selenium.Support.UI;
namespace MyTest
{
[TestClass]
public class MyTest
{
public static IWebDriver Driver = null;
// Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
try
{
string path = Path.GetFullPath(""); // Copy the Chrome driver to the debug
// folder in the bin or set path accordingly
Driver = new ChromeDriver(path);
}
catch (Exception ex)
{
string error = ex.Message;
}
}
// Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyCleanup()
{
Driver.Quit();
}
[TestMethod]
public void MyTestMethod()
{
try
{
string url = "http://www.google.com";
Driver.Navigate().GoToUrl(url);
IWait<IWebDriver> wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(30.00)); // Wait in Selenium
wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath(#"//*[#id='lst - ib']")));
var txtBox = Driver.FindElement(By.XPath(#"//*[#id='lst - ib']"));
txtBox.SendKeys("Google Office");
var btnSearch = Driver.FindElement(By.XPath("//*[#id='tsf']/div[2]/div[3]/center/input[1]"));
btnSearch.Click();
System.Threading.Thread.Sleep(5000);
}
catch (Exception ex)
{
string error = ex.Message;
}
}
}
}
You need to get the Chrome driver from here.
You need to get NuGet packages and necessary DLL files for the Selenium NuGet website.
You need to understand the basics of Selenium from the Selenium documentation website.
That's all...
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using SeleniumAutomationFramework.CommonMethods;
using System.Text;
[TestClass]
public class SampleInCSharp
{
public static IWebDriver driver = Browser.CreateWebDriver(BrowserType.chrome);
[TestMethod]
public void SampleMethodCSharp()
{
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
driver.Url = "http://www.store.demoqa.com";
driver.Manage().Window.Maximize();
driver.FindElement(By.XPath(".//*[#id='account']/a")).Click();
driver.FindElement(By.Id("log")).SendKeys("kalyan");
driver.FindElement(By.Id("pwd")).SendKeys("kalyan");
driver.FindElement(By.Id("login")).Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>(d => d.FindElement(By.LinkText("Log out")));
Actions builder = new Actions(driver);
builder.MoveToElement(driver.FindElement(By.XPath(".//*[#id='menu-item-33']/a"))).Build().Perform();
driver.FindElement(By.XPath(".//*[#id='menu-item-37']/a")).Click();
driver.FindElement(By.ClassName("wpsc_buy_button")).Click();
driver.FindElement(By.XPath(".//*[#id='fancy_notification_content']/a[1]")).Click();
driver.FindElement(By.Name("quantity")).Clear();
driver.FindElement(By.Name("quantity")).SendKeys("10");
driver.FindElement(By.XPath("//*[#id='checkout_page_container']/div[1]/a/span")).Click();
driver.FindElement(By.ClassName("account_icon")).Click();
driver.FindElement(By.LinkText("Log out")).Click();
driver.Close();
}
}
You will need to install Microsoft Visual Studio community Edition
Create a new project as Test Project of C#
Add Selenium references from the NuGet Package Manager. Then you will be all set.
Create a new class and use [Test Class] and [Test Method] annotations to run your script
You can refer to Run Selenium C# | Setup Selenium and C# | Configure Selenium C# for more details.
Use the below code once you've added all the required C# libraries to the project in the references.
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumWithCsharp
{
class Test
{
public IWebDriver driver;
public void openGoogle()
{
// creating Browser Instance
driver = new FirefoxDriver();
//Maximizing the Browser
driver.Manage().Window.Maximize();
// Opening the URL
driver.Navigate().GoToUrl("http://google.com");
driver.FindElement(By.Id("lst-ib")).SendKeys("Hello World");
driver.FindElement(By.Name("btnG")).Click();
}
static void Main()
{
Test test = new Test();
test.openGoogle();
}
}
}

Categories

Resources