Anda di halaman 1dari 36

Initiaing the browser

Log

PageLoad strategy

Profile

Notifications

Certification Error

Proxy
To default download
Firefox
//if path is not set then we need to pass the path of download driver

FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();


service.FirefoxBinaryPath= @"C:\Users\Suresh Srinivasan\AppData\Local\Mozilla Firefox\firefox.exe";
IWebDriver driver = new FirefoxDriver(service);

It creates a new fierfox its own profile, its like a firefox newly installed

FirefoxOptions Options = new FirefoxOptions();


Options.SetLoggingPreference(LogType.Driver, LogLevel.All);
IWebDriver driver = new FirefoxDriver(service,options);

options.PageLoadStrategy = PageLoadStrategy.Eager;

Default - Indicates the behavior is not set.


Eager - Waits for pages to load and ready state to be 'complete'.
None - Waits for pages to load and for ready state to be 'interactive' or 'complete'.
Normal - Does not wait for pages to load, returning immediately.

Exit from File menu


Run -firefox.exe -p profilemanager
Create a new profile[Test]
and start the firefox and add bookmarsk, required extensoin, and settings

options.Profile= new FirefoxProfileManager().GetProfile("Test");

options.SetPreference("dom.webnotifications.enabled", false);

options.AcceptInsecureCertificates = true;

option.SetPreference("network.proxy.type", 1);
option.SetPreference("network.proxy.http", "myproxy.com");
option.SetPreference("network.proxy.http_port", 3239);
String downloadFolderPath = @"c:\temp\";

profile.SetPreference("browser.download.folderList", 2);
profile.SetPreference("browser.download.dir", downloadFolderPath);
profile.SetPreference("browser.download.manager.alertOnEXEOpen", false);
profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/binary,
application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip,
application/x-zip-compressed, application/download, application/octet-stream");
Chrome
IWebDriver driver = new ChromeDriver();

options.AddArguments("start-maximized");

options.BinaryLocation = ""; //Chrome Binary Location


var chromeDriverService = ChromeDriverService.CreateDefaultService();
options.AddArguments("load-extension=/pathTo/extension");

DesiredCapabilitiescapabilities = newDesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilitiesdc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);

options.AddArguments("--log-level=2");
options.AddArguments("--log-net-log=.\\NetLog.log");

options.AddArguments("--disable-infobars");

options.AddArguments("ignore-certificate-errors");
IE
InternetExplorerOptions options = new InternetExplorerOptions() {
    IntroduceInstabilityByIgnoringProtectedModeSettings = true,   
                 EnableNativeEvents = true, 
                    IgnoreZoomLevel = true, 
                   EnsureCleanSession = true}

                 
Iwebdriver driver = new InternetExplorerDriver("path of iedriver",options);  
Edge
edge should be closed before running again
Navigate To URL
RefreshPage
BackPage
ForwardPage

To get title
To get Current URL
To Page source

Set Page Time Out


Implicit wait
Maximize

Explicit Wait

To close Browser not the session

To close Browser and end the session

Locating Eelements

Find multiple elements

Search for an element inside another

Basic Commands on Element


Selecting values in drop down element

To Perfome Mouse and KeyBoad actions

Handle JavaScript pop-ups

Switch to Frames

Switch to windows
Switch between browser windows or tabs

Taking a full-screen screenshot

JavaScript Executor

How To Login Into Any Site If It Is Showing Any Authentication Pop-Up For Username And Password?
Broken links
Driver.Url = "https://www.amazon.in/";
Driver.Navigate().Refresh();
Driver.Navigate().Back();
Driver.Navigate().Forward();

string Title= Driver.Title;


string URL= Driver.Url;
string PageSource= Driver.PageSource;

Driver.Manage().Timeouts().SetPageLoadTimeout(newTimeSpan(10));
Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
Driver.Manage().Window.Maximize();

using ExpectedConditions = SeleniumExtras.WaitHelpers.ExpectedConditions;


WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.AlertIsPresent());

Driver.Close();

Driver.Quit();

driver.FindElement(By.ClassName("className"));

driver.FindElement(By.CssSelector("css"));

driver.FindElement(By.Id("id"));

driver.FindElement(By.LinkText("text"));

driver.FindElement(By.Name("name"));

driver.FindElement(By.PartialLinkText("pText"));

driver.FindElement(By.TagName("input"));

driver.FindElement(By.XPath("//*[@id='editor']"));

IReadOnlyCollection<IWebElement> anchors =driver.FindElements(By.TagName("a"));

vardiv =driver.FindElement(By.TagName("div")) .FindElement(By.TagName("a"));

driver.FindElement(By.Id("id")).Click();
driver.FindElement(By.Id("id")).SendKeys("someText");
driver.FindElement(By.Id("id")).Clear();
driver.FindElement(By.Id("id")).Submit();
Stringinner Text = driver.FindElement(By.Id("id")).Text;
Bool isEnabled = driver.FindElement(By.Id("id")).Enabled;
Bool isDisplayed = driver.FindElement(By.Id("id")).Displayed;
Bool isSelected = driver.FindElement(By.Id("id")).Selected;

SelectElement select = new SelectElement(driver.FindElement(By.Id("id")));


select.SelectByIndex(1);
select.SelectByText("Ford");
select.SelectByValue("ford");
select.DeselectAll();
select.DeselectByIndex(1);
select.DeselectByText("Ford");
select.DeselectByValue("ford");
IWebElementselectedOption = select.SelectedOption;
IList<IWebElement> allSelected = select.AllSelectedOptions;
boolisMultipleSelect = select.IsMultiple;

Actions act = new Actions(driver);


act.Click(driver.FindElement(By.Name("click"))).Build().Perform();
act.MoveToElement(driver.FindElement(By.Name("click"))).Click();

act.DoubleClick(driver.FindElement(By.Name("click"))).Build().Perform();
act.MoveToElement(driver.FindElement(By.Name("click"))).DoubleClick();

act.MoveToElement(driver.FindElement(By.Name("one"))).ClickAndHold() .
MoveToElement(driver.FindElement(By.Name("seven"))).Release().Build().Perform();
act.ClickAndHold(driver.FindElement(By.Name("one"))).
Release(driver.FindElement(By.Name("seven"))).Build().Perform();

act.SendKeys(Keys.Alt + Keys.F4).Build().Perform();

act.DragAndDrop("Elememtsource", "elemnetTarget");

IAlert Alert = driver.SwitchTo().Alert();


Alert.Accept();
alert.Dismiss();
Alert.SendKeys("HI")
string x = Alert.Text;

driver.SwitchTo().Frame("iframe_a");
driver.FindElement(By.Id("name")).SendKeys("hi");
driver.SwitchTo().DefaultContent();

string main = driver.CurrentWindowHandle;


Console.WriteLine(driver.CurrentWindowHandle);
driver.FindElement(By.XPath("//a[contains(text(),'Opens in a new window')]")).Click();
var windows = driver.WindowHandles;
Console.WriteLine( windows.Count );
driver.SwitchTo().Window(windows[1]);
Console.WriteLine(driver.Url);
Console.WriteLine(driver.CurrentWindowHandle);
driver.SwitchTo().Window(main);
Console.WriteLine(driver.Title);

ReadOnlyCollection<string> windowHandles = driver.WindowHandles;


stringfirstTab = windowHandles.First();
stringlastTab = windowHandles.Last();
driver.SwitchTo().Window(lastTab);

Screenshotscreenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile(@"pathToImage", ImageFormat.Png);

JavascriptExecutor js = (JavascriptExecutor) driver;


js.executeScript(Script,Arguments);

js.executeScript("arguments[0].click();", button);
js.executeScript("alert('Welcome to Guru99');");

IWebElement link = driver.FindElement(By.PartialLinkText("Previous post"));


String js= string.Format("window.scroll(0, {0});", link.Location.Y);
((IJavaScriptExecutor)driver).ExecuteScript(js);
link.Click();

To do this we pass username and password with the URL


http://username:password@url
e.g. http://admin:admin123@xyz.com
IReadOnlyCollection<IWebElement> links = driver.FindElements(By.TagName("a"));

foreach (IWebElement link in links)


{
string url = link.GetAttribute("href");
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
try
{
var response = (HttpWebResponse)Request.GetResponse();
System.Console.WriteLine($"URL: {url} status is :{response.StatusCode}");
}
catch (WebException ex)
{
var errorResponse = (HttpWebResponse)ex.Response;
System.Console.WriteLine($"URL: {url} status is :
{errorResponse.StatusCode}");
}
}
Selnium is collection of cl
jsonwire protoal is client

REST API

Click on element
To send text
clear the text on element
to sumit
To get text
To check element is enabled
To check element is displayed
To check element is selected

To click on element

To double click

TO hold and release

To send hot keys

To drag and drop

To click on Yes
To click on No
To send keys on popup
To get the text of pop-up
Selnium is collection of client library avilabe in the form of API for diffreint languages
jsonwire protoal is client over http

REST API
Absolute XPath - / - From root html/body/div[1]/section/div/div/div/div[1]/div/div/div/div/div[3]/div[1]/div/h4[1]/b

Relative XPath - // //a[text()='Testing']

Xpath Methods //input[@name='uid']


//td[text()='UserID']
//*[contains(@type,'sub')]
//*[contains(text(),'here')]
//*[contains(@href,'guru99.com')]
//input[@type='submit' and @name='btnLogin']
//label[starts-with(@id,'message')]
//*[@type='text']//following::input
//*[@type='text']//following::input[1]
//*[text()='Enterprise Testing']//ancestor::div
//*[@id='java_technologies']/child::li[1]
To Get Path

Exceptions

Select dropdown and bootstrap dropdown


string path = new DirectoryInfo(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\" + "Drivers"))).ToString

DriverServiceNotFoundException
ElementNotVisibleException
InvalidCookieDomainException
InvalidElementStateException
InvalidSelectorException
NoAlertPresentException
NoSuchElementException
NoSuchFrameException
NoSuchWindowException
NotFoundException
StaleElementReferenceException
UnableToSetCookieException
UnhandledAlertException
WebDriverException
WebDriverTimeoutException
XPathLookupException

Select dropdown have –<Select > tag


Bootstrap dropdown will have <button, ul, li> tags
OpenQA.Selenium.DriverServiceNotFoundException: 'The IEDriverServer.exe file does not exist in the current directory or in a directory on the PATH environmen
The exception that is thrown when an element is not visible.
The exception that is thrown when the users attempts to set a cookie with an invalid domain.
The exception that is thrown when a reference to an element is no longer valid.
The exception that is thrown when an element is not visible.
The exception that is thrown when an alert is not found.
The exception that is thrown when an element is not found.
The exception that is thrown when a frame is not found.
The exception that is thrown when a window is not found.
The exception that is thrown when an item is not found.
The exception that is thrown when a reference to an element is no longer valid.
The exception that is thrown when the user is unable to set a cookie.
The exception that is thrown when an unhandled alert is present.
Represents exceptions that are thrown when an error occurs during actions.
Represents exceptions that are thrown when an error occurs during actions.
The exception that is thrown when an error occurs during an XPath lookup.
directory on the PATH environment variable. The driver can be downloaded at http://selenium-release.storage.googleapis.com/index.html
Reverse a string string str = "Hello this is suresh";
char[] resultstring = str.ToCharArray(). Reverse().ToArray();
Console.WriteLine(resultstring);

Reverse a string keeping its position string StringToReverse= "Hello this is suresh";
string[] SplitStrings = StringToReverse.Split(' ');
string StringRev = string.Empty;

foreach (var item in SplitStrings)


{
char[] CharStringToReverse = item.ToCharArray();
for (int i = CharStringToReverse.Length - 1; i >= 0; i--)
{
StringRev += CharStringToReverse[i];
}
StringRev +=" ";
}
Console.WriteLine(StringRev);
Console.ReadLine();
Finding pair in array static int sockMerchant(int n, int[] ar)
{
// n = Convert.ToInt32(Console.ReadLine());
//ar =
Array.ConvertAll(Console.ReadLine().Trim().Split(' '), arTemp
=> Convert.ToInt32(arTemp));

Dictionary<int, int> dic = new Dictionary<int, int>();


int count = 0;
foreach (var item in ar)
{
if (dic.ContainsKey(item))
{
dic[item] = dic[item] + 1;
}
else
dic.Add(item, count + 1);

};
int pair = 0;

foreach (var item in dic)


{
if (item.Value / 2 >= 1)
{
pair += item.Value / 2;
}

Console.WriteLine(pair);

Console.ReadKey();
return pair;
}
Key = s.Attribute("Key").Value,
Reading XML Value = s.Attribute("Value").Value
});

NameValueCollection GlobalSetting = new


NameValueCollection();

globalSettings.ToList().ForEach(s =>
{
GlobalSetting.Add(s.Key, s.Value);
});

foreach (var item in GlobalSetting)


{
Console.WriteLine(item + ": " +
GlobalSetting[item.ToString()]);
}

NameValueCollection RunSetting = new


NameValueCollection();

runSettings.ToList().ForEach(s =>
{
RunSetting.Add(s.Key, s.Value);
});

foreach (var item in RunSetting)


{
Console.WriteLine(item + ": " +
RunSetting[item.ToString()]);
}

Console.ReadLine();

}
Reading Json Managenuget : Newtonsoft.Json
Refernce System.Web.Extension

using System.Web.Script.Serialization;
using System.IO;
using Newtonsoft.Json;

Create- SETTING CS file


string JsonData =
File.ReadAllText(@"D:\1Learning\CSharp\Projects\CSharpLe
arning\SeleniumLearning\FrameWork\AppSettings.json");
JavaScriptSerializer ser = new JavaScriptSerializer();
RunSettings settings =
ser.Deserialize<RunSettings>(JsonData);
string StringToReverse= "Hello this is suresh";
char[] CharStringToReverse = StringToReverse.ToCharArray();
string StringRev = string.Empty;
for (int i = CharStringToReverse.Length - 1; i >= 0; i--)
{
StringRev += CharStringToReverse[i];
}
Console.WriteLine(StringRev);
Console.ReadLine();
Linq
Aggrigate Min Console.WriteLine(numbers.Min());

int[] numbers = { 11, 2, 3, 4, 1, 5, 6, 7, 8, 9 }; Max Console.WriteLine(numbers.Max());

Sum Console.WriteLine(numbers.Sum());

Count Console.WriteLine(numbers.Count());
Average Console.WriteLine(numbers.Average());
WithoutLinq Linq
int[] numbers = { 11, 2, 3, 4, 1, 5, 6, 7, 8, 9 }; Console.WriteLine(numbers.Where(x => x % 2 == 0).Min());
int? min = null;
foreach (int number in numbers)
{
if (!min.HasValue || min<number)
{
min = number;
}
}
Console.WriteLine(min);

int[] numbers = { 11, 2, 3, 4, 1, 5, 6, 7, 8, 9 }; Console.WriteLine(numbers.Where(x => x % 2 == 0).Max());


int? min = null;
foreach (int number in numbers)
{
if (!min.HasValue || min>number)
{
min = number;
}
}
Console.WriteLine(min);

int sum = 0;
foreach (int number in numbers)
{
sum += number;

}
Console.WriteLine(sum);

Console.WriteLine(numbers.Length);
WithoutLinq
int[] numbers = { 11, 2, 3, 4, 1, 5, 6, 12,17, 8, 9 };
int? min = null;
foreach (int number in numbers)
{
if (number%2==0)
{
if (!min.HasValue || min < number)
{
min = number;
}

}
}
Console.WriteLine(min);

Anda mungkin juga menyukai