I'm looking to write a program that opens up an instance of Firefox, namely the default instance of Firefox that contains my various login information, and then simply switch through a few sites. I'm sort of able to do this, using the following code:
System.Diagnostics.Process.Start("firefox.exe", "thisIsMyURL");
However, as I'm sure you're mostly aware, this simply opens a new Firefox process with the given URL as a default site to open to. In order to do what I want, I'd essentially have to open a new Firefox process, do what I need to on the page, kill the process, and repeat this for each page I need. This is less than ideal. So, I'm hoping that someone will know of a way to programmatically control Firefox, through an API or library or something. I've searched on Google, and so far have only found outdated solutions that didn't really solve my problem in the first place.
As always, thanks for your help! Everything you can offer is appreciated.
You can use Selenium WebDriver for C #.
This is a cross-platform API that allows you to control various browsers using APIs for Java, C#, among others.
Attachment of a code C # with Selenium WebDriver tests.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.IE;
using NUnit.Framework;
using System.Text.RegularExpressions;
namespace sae_test
{ class Program
{ private static string baseURL;
private static StringBuilder verificationErrors;
static void Main(string[] args)
{ // test with firefox
IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();
// test with IE
//InternetExplorerOptions options = new InternetExplorerOptions();
//options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
//IWebDriver driver = new OpenQA.Selenium.IE.InternetExplorerDriver(options);
SetupTest();
driver.Navigate().GoToUrl(baseURL + "Account/Login.aspx");
IWebElement inputTextUser = driver.FindElement(By.Id("MainContent_LoginUser_UserName"));
inputTextUser.Clear();
driver.FindElement(By.Id("MainContent_LoginUser_UserName")).Clear();
driver.FindElement(By.Id("MainContent_LoginUser_UserName")).SendKeys("usuario");
driver.FindElement(By.Id("MainContent_LoginUser_Password")).Clear();
driver.FindElement(By.Id("MainContent_LoginUser_Password")).SendKeys("123");
driver.FindElement(By.Id("MainContent_LoginUser_LoginButton")).Click();
driver.Navigate().GoToUrl(baseURL + "finanzas/consulta.aspx");
// view combo element
IWebElement comboBoxSistema = driver.FindElement(By.Id("MainContent_rcbSistema_Arrow"));
//Then click when menu option is visible
comboBoxSistema.Click();
System.Threading.Thread.Sleep(500);
// container of elements systems combo
IWebElement listaDesplegableComboSistemas = driver.FindElement(By.Id("MainContent_rcbSistema_DropDown"));
listaDesplegableComboSistemas.FindElement(By.XPath("//li[text()='BOMBEO MECANICO']")).Click();
System.Threading.Thread.Sleep(500);
IWebElement comboBoxEquipo = driver.FindElement(By.Id("MainContent_rcbEquipo_Arrow"));
//Then click when menu option is visible
comboBoxEquipo.Click();
System.Threading.Thread.Sleep(500);
// container of elements equipment combo
IWebElement listaDesplegableComboEquipos = driver.FindElement(By.Id("MainContent_rcbEquipo_DropDown"));
listaDesplegableComboEquipos.FindElement(By.XPath("//li[text()='MINI-V']")).Click();
System.Threading.Thread.Sleep(500);
driver.FindElement(By.Id("MainContent_Button1")).Click();
try
{ Assert.AreEqual("BOMBEO MECANICO_22", driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_LabelSistema\"]")).Text);
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
// verify coin format $1,234,567.89 usd
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelInversionInicial\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoOpMantto\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelcostoUnitarioEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
// verify number format 1,234,567.89
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelConsumo\"]")).Text, "((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})?"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
System.Console.WriteLine("errores: " + verificationErrors);
System.Threading.Thread.Sleep(20000);
driver.Quit();
}
public static void SetupTest()
{ baseURL = "http://127.0.0.1:8081/ver.rel.1.2/";
verificationErrors = new StringBuilder();
}
protected static void mouseOver(IWebDriver driver, IWebElement element)
{ Actions builder = new Actions(driver);
builder.MoveToElement(element);
builder.Perform();
}
public static void highlightElement(IWebDriver driver, IWebElement element)
{ for (int i = 0; i < 2; i++)
{ IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);",
element, "color: yellow; border: 2px solid yellow;");
js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);",
element, "");
}
}
}
}
download at http://vidadigital.com.mx/publicacion/source/Program.cs
I was reading MSDN magazine a while back, and I saw an article about a project called "Watir" that piqued my interested, because I was doing a lot of automated testing at the time. I looked into it and found there is actually a project called WatiN which is .NET based. Check it out I think it is exactly what you're looking to do.
http://watin.org/
http://watir.com/
First start the process using :
Process.Start("firefox.exe", "www.example.com");
Then to kill it you need to do next:
Process[] processes = Process.GetProcessesByName("firefox.exe");
foreach (Process p in processes)
{
if (p.ProcessName.Equals("firefox.exe", StringComparison.OrdinalIgnoreCase))
{
p.Kill();
}
}
Related
Hi everyone recently my mom created instagram account for his work and I want to make him auto follower bot in selenium but whenever I try to test this few times instagram just locks me out by saying Please try again in few minutes but It just keeps saying after 5-10-20 minutes even hours any suggestions ? How can I test this ?
With this code just logs in and scroll down in main page where you can follow people by randomly but I cant follow all of them , how can I adress follow button every time ?
using System;
using System.Collections.Generic;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace InstagramFollower
{
class Program
{
private static readonly string Pusername = "sorrycantshare";
private static readonly string Ppassword = "sorrycantshare";
private static int sayac = 1;
public static IWebDriver driver = new ChromeDriver();
static void Main()
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(100));
driver.Navigate().GoToUrl("https://www.instagram.com/");
//driver.Manage().Window.Maximize();
Console.WriteLine("Siteye açıldı");
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Name("username")));
IWebElement username = driver.FindElement(By.Name("username"));
IWebElement password = driver.FindElement(By.Name("password"));
IWebElement loginbtn = driver.FindElement(By.CssSelector(".Igw0E.IwRSH.eGOV_._4EzTm"));
username.SendKeys(Pusername);
password.SendKeys(Ppassword);
loginbtn.Click();
Console.WriteLine("Hesaba giriş yapıldı");
ElementToClickableCssSelector(".sqdOP.L3NKy.y3zKF");
driver.Navigate().GoToUrl($"https://www.instagram.com");
Console.WriteLine("Anasayfaya yönlendirildi");
ElementToClickableCssSelector(".aOOlW.HoLwm");
IWebElement notNow = driver.FindElement(By.CssSelector(".aOOlW.HoLwm"));
notNow.Click();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight);");
Thread.Sleep(1500);
js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight);");
Thread.Sleep(2500);
ElementToClickableCssSelector(".Szr5J._6CZji");
Listpeople();
Thread.Sleep(3500);
/*
IWebElement followbtn = driver.FindElement(By.CssSelector(".sqdOP.L3NKy._4pI4F.y3zKF"));
followbtn.Click(); // It follows first person on line but It gives error for others.
*/
}
public static void Listpeople()
{
IReadOnlyCollection<IWebElement> followersname = driver.FindElements(By.CssSelector(".FPmhX.notranslate.Qj3-a"));
IWebElement nextbtn = driver.FindElement(By.CssSelector(".Szr5J._6CZji"));
foreach (IWebElement follower in followersname)
{
Console.WriteLine(sayac.ToString() + " ==> " + follower.Text);
sayac++;
if (sayac == 8)
{
nextbtn.Click();
}
}
}
public static void ElementToClickableCssSelector(string target)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(100));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.CssSelector(target)));
}
}
}
Well I had to read some topics about it turns out instagram detects selenium webdriver but I belive in my case is different.Reason I got error of please try again in later is beacuse my account does not log out , every time I log in and test after I stop building and shutdown cmd and browser so It doesnt log out.I am now writing a void to log out for after I test it
I'm asking for help, I'm already desperate.
I made a simple test script with Gherkin and generated the steps. I want to integrate Applitools into this process, that is, to use eyes.Check() method. But no matter how hard I try, every time I initialize the eyes object, I get the following error: Method not found: "Applitools.BatchInfo Applitools.IEyesBase.get_Batch().
Examples on applitools.com don't fit me, because the same Ruby implementation doesn't work for me, and the C# example doesn't involve using Gherkin.
My scenario:
#Default.Target.Environment:Edu
Feature: LoginScenario
#INWK.LP.C0002
Scenario: L001_Login
When I open Web Site
And I login as user my_email#edu.hse.ru with pass 12345678
Then I close browser
My steps:
using System.Drawing;
using Applitools;
using Applitools.Selenium;
using Lms.Helpers;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using TechTalk.SpecFlow;
using NUnit.Framework;
using Configuration = Applitools.Selenium.Configuration;
namespace Lms.Steps
{
[TestFixture]
[Binding]
public class LoginInLmsSteps
{
private IWebDriver driver;
private LoginHelper loginHelper;
private Eyes eyes;
private EyesRunner runner;
private string Url => "https://lms.hse.ru/";
[Before]
[SetUp]
public void BeforeEach()
{
Configuration config = new Configuration();
config.SetApiKey("my_key");
config.SetBatch(new BatchInfo("LMS Batch"));
config.AddBrowser(800, 600, BrowserType.CHROME);
runner = new ClassicRunner();
eyes = new Eyes(runner);
eyes.SetConfiguration(config);
}
[When(#"I open Web Site")]
public void WhenIOpenWebSite()
{
driver = new ChromeDriver();
driver.Url = Url;
}
[When(#"I login as user (.*) with pass (.*)")]
public void WhenILoginAsUserWithPass(string username, string password)
{
eyes.Open(driver, "LMS", "Login test", new Size(800, 600));
eyes.CheckWindow("Login Page");
loginHelper.Login(username, password);
eyes.CloseAsync();
}
[Then(#"I close browser")]
public void ThenICloseBrowser()
{
driver.Quit();
driver = null;
}
[TearDown]
public void AfterEach()
{
// If the test was aborted before eyes.close was called, ends the test as aborted.
eyes.AbortIfNotClosed();
//Wait and collect all test results
TestResultsSummary allTestResults = runner.GetAllTestResults();
}
}
}
That is, I catch the error already at the setup stage
I would be grateful for any help!
I had asked a question some time back and I am still facing random errors trying to parse a webpage.
The scenario is that the system goes to https://www.sprouts.com/store/tx/plano/plano/ clicks on "VIEW THIS STORE’S SPECIALS" navigates to https://shop.sprouts.com/shop/flyer and extracts the stores specials. Currently the code below works 10% or 20% of the times only as it is unable to find the button to click and navigate to the next page.
What am i doing wrong?
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using SeleniumExtras.WaitHelpers;
[TestClass]
public class UnitTest1
{
ChromeDriver driver;
WebDriverWait webDriverWait;
[TestInitialize]
public void Startup()
{
var chromeOptions = new ChromeOptions();
//chromeOptions.AddArguments("headless");
chromeOptions.AddArguments("--proxy-server='direct://'");
chromeOptions.AddArguments("--proxy-bypass-list=*");
//chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");
//chromeOptions.AddArguments("--disable-extensions");
chromeOptions.AddArguments("--start-maximized");
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService(path);
driver = new ChromeDriver(chromeDriverService, chromeOptions);
webDriverWait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
}
[TestCleanup]
public void CleanUp()
{
driver.Quit();
}
[TestMethod]
public void GetSproutsWeeklyAdDetails()
{
try
{ driver.Navigate().GoToUrl("http://www.sprouts.com/store/tx/plano/plano/");
}
catch (TimeoutException timeoutException)
{
driver.Navigate().Refresh();
}
webDriverWait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
**var elements1 = webDriverWait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(
By.XPath("//div[#class='cell small-6 divider']/button")));
elements1.First().Click();**
<= the system is unable to find the button 80% of the times
webDriverWait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
var elements2 = webDriverWait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(
By.XPath("//li[#class='cell-wrapper' and #ng-repeat='item in items track by $index']")));
//More code below
}
}
}
source code of area where button that is not clickable:
<div class="cell small-6 divider">
<button onclick="viewStoreFlyer(event, 101)">
<img src="https://www.sprouts.com/wp-content/themes/FoundationPress/dist/assets/images/weekly-specials-stores-icon.svg" width="32" alt="" role="presentation">
<br>
View this store’s specials
</button>
</div>
In my perpesctive the code is almost good, except two things. You are waiting for all elements to be visible and then immediately want to click on the first of them. Firstly on the website is only one element with following xPath, so there is no need to locate a list. The second is - when element is visible, it does not means it is clickable, so the better way to deal with this would be:
webDriverWait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[#class='cell small-6 divider']/button")));
PS: the answer #DebanjanB has provided is very good in that case, since you just wanted to extract the text withoun interacting with element. In our case we have to wait until elelment will be ready to recieve a click, that's why ElementToBeClickable is better in this case.
I was able to get this working by adding a thread sleep just before the button was clicked.
var elements1 = webDriverWait.Until(ExpectedConditions.ElementToBeClickable(
By.XPath("//div[#class='cell small-6 divider']/button")));
Thread.Sleep(2000);
elements1.Click();
Due to the lack of proper documentation, I'm not sure if HtmlAgilityPack supports screen capture in C# after it loads the html contents.
So is there a way I can more or less grab a screenshot using (or along with) HtmlAgilityPack so I can have a visual clue as to what happens every time I do page manipulations?
Here is my working code so far:
using HtmlAgilityPack;
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string urlDemo = "https://htmlagilitypack.codeplex.com/";
HtmlWeb getHtmlWeb = new HtmlWeb();
var doc = getHtmlWeb.Load(urlDemo);
var sentence = doc.DocumentNode.SelectNodes("//p");
int counter = 1;
try
{
foreach (var p in sentence)
{
Console.WriteLine(counter + ". " + p.InnerText);
counter++;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}
Currently, it scrapes and output all the p of the page in the console but at the same time I want to get a screen grab of the scraped contents but I don't know how and where to begin.
Any help is greatly appreciated. TIA
You can't do this with HTML Agility Pack. Use a different tool such as Selenium WebDriver. Here is how to do it: Take a screenshot with Selenium WebDriver
Could you use Selenium WebDriver instead?
You'll need to add the following NuGet packages to your project first:
Selenium.WebDriver
Selenium.Support
Loading a page and taking a screenshot is then as simple as...
using System;
using System.Drawing.Imaging;
using System.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
// Create a web driver that used Firefox
var driver = new FirefoxDriver(
new FirefoxBinary(), new FirefoxProfile(), TimeSpan.FromSeconds(120));
// Load your page
driver.Navigate().GoToUrl("http://google.com");
// Wait until the page has actually loaded
var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 10));
wait.Until(d => d.Title.Contains("Google"));
// Take a screenshot, and saves it to a file (you must have full access rights to the save location).
var myDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(Path.Combine(myDesktop, "google-screenshot.png"), ImageFormat.Png);
driver.Close();
}
}
}
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();
}
}
}