MultiThreading Variables C# -- Selenium - c#

I am trying to automate the test for one of my websites using Selenium on C#. The website prompts the user for login credentials. It can only be done through multi threading.
I execute one thread to open the page in a special FireFox profile and another thread in parallel to simulate the press of ENTER.
The problem is the if I don't use multi threading, the code stops at opening the page as the website is not completely opened.
The driver is initiated in the first thread created. However it has to be used in the main method.
How can I pass an object created in a method (executed by a thread) in the main function?
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System.Collections.ObjectModel;
using System.Threading;
using System.IO;
using OpenQA.Selenium.Interactions;
using System.Windows.Forms;
namespace CRMTest1WithSelenium
{
class Program
{
public static IWebDriver OpenPage()
{
IWebDriver driver = null;
string path = #"C:\Users\ntouma\AppData\Roaming\Mozilla\Firefox\Profiles\nuxgc36b.CRMTester";
FirefoxProfile ffprofile = new FirefoxProfile(path);
driver = new FirefoxDriver(ffprofile);
driver.Navigate().GoToUrl("http://www.example.com");
return driver;
}
public static void pressEnter()
{
Thread.Sleep(6000);
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
}
static void Main(string[] args)
{
IWebDriver driver2 = null;
driver2 = OpenPage();
// Thread driverCreation = new Thread(OpenPage);
// driverCreation.Start();
Thread login = new Thread(pressEnter);
login.Start();
Thread.Sleep(2000);
driver2.Manage().Window.Maximize();
IWebElement sales = driver2.FindElement(By.XPath("/html/body/div[4]/d"));
sales.Click();
IWebElement leads = driver2.FindElement(By.XPath("/html/body//div/div/ul/li[3]/span/span[2]/span/span[1]/span/a[1]"));
leads.Click();
Thread.Sleep(5000);
}
}
}

Well i don't understand your problem in 100%...
But i can suggest two solutions:
1) Use a static member that your login functions will use inside it.
2) Send a class(object) to the thread when you create one:
e.g:
var myObj = ...; Thread thread = new Thread(() => pressEnter(myObj)); thread.Start();

Related

How to Find the reCAPTCHA element and click on it in c# Selenium

Hello everyone I need some help. There is URL: http://lisans.epdk.org.tr/epvys-web/faces/pages/lisans/petrolBayilik/petrolBayilikOzetSorgula.xhtml. As you can see in screenshot I need to click checkbox Captcha.
https://i.stack.imgur.com/xjXaA.png
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace AkaryakitSelenium
{
class Program
{
private static string AkaryakitLink = "http://lisans.epdk.org.tr/epvys-web/faces/pages/lisans/petrolBayilik/petrolBayilikOzetSorgula.xhtml";
static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
driver.Navigate().GoToUrl(AkaryakitLink);
var kategoriCol = driver.FindElements(By.CssSelector(".ui-selectonemenu-trigger.ui-state-default.ui-corner-right"));
var x = kategoriCol[3];
x.Click();
var deneme = driver.FindElement(By.Id("petrolBayilikOzetSorguKriterleriForm:j_idt52_1"));
deneme.Click();
var check = driver.FindElement(By.Id("recaptcha-anchor"));
check.Click();
}
}
}
And lastly this error that I am facing:
"OpenQA.Selenium.NoSuchElementException: 'no such element: Unable to
locate element: {"method":"css
selector","selector":"#recaptcha-anchor"}"
Thank you for your help.
The element you are looking for is inside an iframe :
//iframe[#title='reCAPTCHA']
first you need to switch to iframe like this :
new WebDriverWait(driver, TimeSpan.FromSeconds(3)).Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.XPath("//iframe[#title='reCAPTCHA']")));
then you can perform a click on it :
var check = driver.FindElement(By.Id("recaptcha-anchor"));
check.Click();
PS : captchas are not meant to be automated. since Captcha stands for CAPTCHA stands for the Completely Automated Public Turing test to tell Computers and Humans Apart.
You can not bypass captcha with Selenium.
It is designed to avoid automated access to web pages as described here and in many other places.

C# Selenium bot element selection trouble

I am trying to make a bot that goes through drop-downs and makes selections but it's having trouble finding the element. The code is below.
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.Extensions;
using OpenQA.Selenium.Support.UI;
namespace selenium_test
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver;
driver = new ChromeDriver("C:\\");
Console.WriteLine("ChromeDriver Initialized");
driver.Url = "https://odyssey.gwinnettcourts.com/Portal/Home/Dashboard/26";
IWebElement typeElement = driver.FindElement(By.XPath(".//option[#id='cboHSSearchBy']"));
var typeSelect = new SelectElement(typeElement);
typeSelect.SelectByValue("JudicialOfficer");
typeElement.Click();
}
}
}
what exactly is the error? I can only assume that it is taking time to find element.
add wait time maybe? also, why using xpath when you have id of controls? id is quicker!
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists((By.Id("cboHSSearchBy"))));

addScriptToEvaluateOnNewDocument Selenium (Does not work)

I need to execute addScriptToEvaluateOnNewDocument method of Google Headless Chrome in C# .Net. I basically need to execute Javascript before any other javascript is executed on the documents. Here is my code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
namespace User
{
class Program
{
//public static IWebDriver driver = new ChromeDriver();
public static IWebDriver driver;
public static double magnification = 2;
static void Main(string[] args)
{
ChromeOptions options = new ChromeOptions();
//options.AddArgument("Page.addScriptToEvaluateOnNewDocument");
options.AddArgument("--window-size=1920,1080");
options.AddUserProfilePreference("Page.addScriptToEvaluateOnNewDocument", "alert('INJECTED SCRIPT')");
driver = new ChromeDriver(options);
var action = new OpenQA.Selenium.Interactions.Actions(driver);
System.Threading.Thread.Sleep(1000);
driver.Navigate().GoToUrl("https://google.com");
System.Threading.Thread.Sleep(10000);
}
}
}
But the alert isn't fired (i have tried other JavaScript code besides alert - nothing seems to work)
Try this.After initialize the driver.Hope this will work.
driver.ExecuteJavaScript("alert(0);")
OR
driver.Scripts().ExecuteScript("alert(0);")
I have only done this in Python but it should work the same way.
The chromedriver should expose a function named execute_cdp_cmd()
You can use this to run JavaScript before the page JavaScript is run. See the python example below. Note that you should add the code shown below after creating the driver but before you get the web page.
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
alert(0);
"""
})
I don't have a C# example, but this might help.
using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.DevTools.V91.Page;
using OpenQA.Selenium.Support.UI;
using RandomNameGeneratorLibrary;
using Network = OpenQA.Selenium.DevTools.V91.Network;
using DevToolsSessionDomains = OpenQA.Selenium.DevTools.V91.DevToolsSessionDomains;
IDevTools devTools = driver as IDevTools;
session = devTools.GetDevToolsSession();
var domains = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
domains.Page.AddScriptToEvaluateOnNewDocument(new AddScriptToEvaluateOnNewDocumentCommandSettings()
{
Source = jscode,
});

Getting an Exception System.ComponentModel.Win32Exception : The system cannot find the file specified in Sikuli C#

I am getting an exception System.ComponentModel.Win32Exception : The system cannot find the file specified when i employ Sikuli in C# using selenium.
I have referred to other posts in Stack but i have not not got a solution for that.
I am also running VS 2017 in administrator mode
I have latest copy of Rest-Api Jar in /Debug folder.
Below is my code
using System;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using Sikuli4Net.sikuli_REST;
using Sikuli4Net.sikuli_UTIL;
using SikuliModule;
namespace DownloadFile
{
public class Download
{
private IWebDriver driver;
private APILauncher launcher;
[SetUp]
public void setup()
{
driver = new FirefoxDriver();
launcher = new APILauncher(true);
driver.Navigate().GoToUrl("https://java.com/en/download/");
driver.Manage().Window.Maximize();
}
[Test]
public void TestMethod1()
{
new WebDriverWait(driver, TimeSpan.FromSeconds(60)).Until(ExpectedConditions.ElementExists((By.XPath("//span[contains(text(),'Free Java Download')]")))).Click();
new WebDriverWait(driver, TimeSpan.FromSeconds(60)).Until(ExpectedConditions.ElementExists((By.XPath("//span[contains(text(),'Agree and Start Free Download')]")))).Click();
launcher.Start();
Screen screen = new Screen();
Pattern Click_Save = new Pattern("C:/Selenium Files/Save.jpg");
screen.Wait(Click_Save, 500);
screen.Click(Click_Save);
launcher.Stop();
}
}
}
Update your path of .jpg file in below line of code:
Pattern Click_Save = new Pattern("C:\\Selenium Files\\Save.jpg");
Rest of the code seems fine.

OpenQA.Selenium.NoSuchElementException was unhandled + C# + Another Website

I am new to selenium, currently exploring on how it works. Started using it for ASP.NET application, i am using C# Selenium driver, IE Driver server ( 32 bit as it's faster than 64 bit)
I navigated to a application there I am clicking a link which should take me to ANOTHER WEBSITE where I have to find a textbox and clear it and enter some text (SendKeys) and then click a button.
When it goes to a another website from main website, It's unable to find the element ( I tried using by.ID and by.Name). I made sure element is available on the webpage. As recommened I used ImplicitlyWait but no luck, tried thread.sleep() no lucK.. Does the test needs to be on the same website which launched initially ?.. Below is my code snippet.. Please help me..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using System.Threading;
namespace mySelenium
{
class Program
{
private static void Main(string[] args)
{
IWebDriver driver = new InternetExplorerDriver(#"C:\Users\msbyuva\Downloads\IEDriverServer_Win32_2.45.0\");
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
driver.Navigate().GoToUrl("http://MyorgName.org/Apps/Sites/2015/login.aspx");
IWebElement userNameTxtBox = driver.FindElement(By.Id("ContentPlaceHolder1_Login1_UserName"));
userNameTxtBox.SendKeys("MSBYUVA");
IWebElement passwordTxtBox = driver.FindElement(By.Id("ContentPlaceHolder1_Login1_Password"));
passwordTxtBox.SendKeys("1234");
var myButton = driver.FindElement(By.Id("ContentPlaceHolder1_Login1_LoginButton"));
myButton.Click();
var EMailLink = driver.FindElement(By.LinkText("Email Testing Link"));
EMailLink .Click();
//Thread.Sleep(10000);
// -- HERE IT IS THROWING ERROR (ANOTHER WEBSITE AFTER CLICKING HYPERLINK)
var toEmailAddress = driver.FindElement(By.Name("ctl00$ContentPlaceHolder1$txtTo"));
toEmailAddress.Clear();
toEmailAddress.SendKeys("msbyuva#gmail.com");
var chkEmailAttachment = driver.FindElement(By.Name("ctl00$ContentPlaceHolder1$ChkAttachMent"));
chkEmailAttachment.Click();
var sendEmailButton = driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_BtnSend"));
sendEmailButton.Click();
}
}
}
You need to switchTo newly opened window and set focus to it in order to send any commands to it
string currentHandle = driver.CurrentWindowHandle;
driver.SwitchTo().Window(driver.WindowHandles.ToList().Last());
After you done with newly opened window do(as need)
driver.Close();
driver.SwitchTo().Window(currentHandle );
More perfectly use PopupWindowFinder class
string currentHandle = driver.CurrentWindowHandle;
PopupWindowFinder popUpWindow = new PopupWindowFinder(driver);
string popupWindowHandle = popUpWindow.Click(EMailLink );
driver.SwitchTo().Window(popupWindowHandle);
//then do the email stuff
var toEmailAddress = driver.FindElement(By.Name("ctl00$ContentPlaceHolder1$txtTo"));
toEmailAddress.Clear();
toEmailAddress.SendKeys("msbyuva#gmail.com");
var chkEmailAttachment = driver.FindElement(By.Name("ctl00$ContentPlaceHolder1$ChkAttachMent"));
chkEmailAttachment.Click();
var sendEmailButton = driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_BtnSend"));
sendEmailButton.Click();
}
}
}
//closing pop up window
driver.Close();
driver.SwitchToWindow(currentHandle);

Categories

Resources