Selenium C# Can't find ID or Title - c#

I manage to open a firefox browser, go to http://www.google.com/ search for "Bath Fitter". When i see a bunch of links, i want to in fact click on an item of the top menu provided by Google, Images. Images is located next to Map Videos News...
How can i have it click on Images?
Below 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.Firefox;
namespace SeleniumHelloWorld
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = null;
try
{
driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com/");
driver.Manage().Window.Maximize();
IWebElement searchInput = driver.FindElement(By.Id("gbqfq"));
searchInput.SendKeys("Bath Fitter");
searchInput.SendKeys(Keys.Enter);
searchInput.FindElement(By.Name("Images"));
searchInput.Click();
driver.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception ****" + e.ToString());
}
}
}
}

More specifically you can also write your selector pointing from Top Navigation. This is the XPath.
.//*[#id='hdtb_msb']//a[.='Images']
try this;
driver.FindElement(By.XPath(".//*[#id='hdtb_msb']//a[.='Images']"));
EDIT:
Even though the selectors above were correct your code was not working because of the second page was taking too long to load. There you need to wait for the the element to be in ready state and an implicit wait is needed. Change the code in your try block and replace with mine and try
driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com/");
driver.Manage().Window.Maximize();
IWebElement searchInput = driver.FindElement(By.Id("gbqfq"));
searchInput.SendKeys("Bath Fitter");
searchInput.SendKeys(Keys.Enter);
//this is the magic
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
By byImage = By.XPath(".//*[#id='top_nav']//a[.='Images']");
IWebElement imagElement =
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(byImage));
imagElement.Click();

Try something like this...
IList<IWebElement> links = driver.FindElements(By.TagName("a"));
links.First(element => element.Text == "Images").Click();

Related

C# Automation Edge Browser - using Edge Driver - auto testing program - Failure: No matching capabilities found (SessionNotCreated)

Greetings stackoverflow community,
I am trying to compile and run the programcode from this website:
https://social.msdn.microsoft.com/Forums/en-US/7bdafd2a-be91-4f4f-a33d-6bea2f889e09/c-sample-for-automating-ms-edge-chromium-browser-using-edge-web-driver
I followed all the instructions listed in the link and set my paths were I wanted them.
The program and the edge driver starts running, but then an error appears.
"An error exeption "System.InvalidOperationException" appeared in WebDriver.dll.
Further Inforamtion: session not created: No matching capabilities found (SessionNotCreated)"
This is the code from my program, more or less copied from the link above:
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.Edge;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var anaheimService = ChromeDriverService.CreateDefaultService(#"C:\edgedriver_win64", "msedgedriver.exe");
// user need to pass the driver path here....
var anaheimOptions = new ChromeOptions
{
// user need to pass the location of new edge app here....
BinaryLocation = #"
C: \Program Files(x86)\Microsoft\Edge\Application\msedge.exe "
};
IWebDriver driver = new ChromeDriver(anaheimService, anaheimOptions); -- error appears at this line
driver.Navigate().GoToUrl("https: //google.com/");
Console.WriteLine(driver.Title.ToString());
driver.Close();
}
}
}
I would really appreciate your help!
Best Regards
Max
The article you refer to is a bit out of date. Now we don't need to use ChromeDriver to automate Edge. You can refer to the official doc about how to use WebDriver to automate Microsoft Edge.
I recommend using Selenium 4. Here I install Selenium 4.1.0 NuGet package and the sample C# code is like below:
using System;
using OpenQA.Selenium.Edge;
namespace WebDriverTest
{
class Program
{
static void Main(string[] args)
{
var options = new EdgeOptions();
options.BinaryLocation = #"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe";
var driver = new EdgeDriver(#"C:\edgedriver_win64", options);
driver.Navigate().GoToUrl("https://www.google.com");
Console.WriteLine(driver.Title.ToString());
driver.Close();
}
}
}

Selenium C# Not able to redirect after the click for login

I met problems of not able to log in with selenium. I think the login button is clicked successfully. But the website that I am testing against has some login-check or rest-assured Ajax handling which I don't know. So after I click the login button on the website, I am not able to log in and redirect. I am not sure what's going on.
The website I am practising is https://www.catch.com.au/.
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System.Threading;
using System;
namespace Selenium429ErrorDemo
{
public class Tests
{
string url = "https://www.catch.com.au/";
private IWebDriver _driver;
[Test]
public void Test1()
{
_driver = new ChromeDriver();
_driver.Navigate().GoToUrl(url);
_driver.Manage().Window.Maximize();
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(30));
_driver.FindElement(By.CssSelector("[data-testid='myaccount-reference']")).Click();
_driver.FindElement(By.Id("login_email")).SendKeys("EMAIL");
_driver.FindElement(By.Id("login_password")).SendKeys("PASSWORD");
IWebElement btn = _driver.FindElement(By.Id("button-login"));
wait.Until(ExpectedConditions.ElementToBeClickable(btn));
btn.Click();
IWebElement ert = _driver.FindElement(By.CssSelector(".css-n11h0l"));
wait.Until(ExpectedConditions.UrlMatches("https://www.catch.com.au/"));
}
}
}

I facing problem open dropdown select option on click in c# using selenium

I am trying to open the Register page from my account.
The UI developer used the bootstrap code. Bootstrap developers have added the JS function on click.
and when I run this code then show error "OpenQA.Selenium.ElementClickInterceptedException has been thrown
element click intercepted: Element ... is not clickable at point (984, 50). Other element would receive the click: ...
(Session info: chrome=77.0.3865.120)"
Attached Screenshot link:
https://monosnap.com/file/1z5PYCFBHfcXtkWJWVMi4SeejUXXOf
https://monosnap.com/file/hdq3194312RCnvc6GdQXLLVqtoezNJ
This my code
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace XTSeleniumtest
{
class MainClass
{
public static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://freshpicksdev.isrv.tech/");
driver.FindElement(By.CssSelector("div.modal-header .close")).Click();
driver.FindElement(By.XPath("//a[#id='navbarDropdown']/u")).Click();
}
}
}
**`
> strong text
`**
You can wait until the element is visible.
driver.FindElement(By.XPath("//a[#id='navbarDropdown']/u"));
If still the issue exists please post the DOM structure of your web page,it may be related to interacting with a wrong element.
Try the below code. You would need to add reference for "SeleniumExtras.WaitHelpers" from nuget
class MainClass
{
public static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://freshpicksdev.isrv.tech/");
driver.FindElement(By.CssSelector("div.modal-header .close")).Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.XPath("//u[contains(text(),'My Account')]")));
driver.FindElement(By.XPath("//u[contains(text(),'My Account')]")).Click();
driver.FindElement(By.XPath("//a[text()='Register']")).Click();
}
}

Exception 'Element should have been select but was div' C# selenium

I'm getting an exception with a piece of code. My code is adding an item to a bag then I want to select the quantity of the item. When I click on the quantity on the drop down menu to select 2.
My code throws an exception on this line:
IWebElement Qty = webDriver.FindElement(By.Id("bagApp"));
SelectElementFromDropDown(Qty, "2");
Element should have been select but was div.
This piece of code is designed to click on the drop down menu.
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;
using OpenQA.Selenium.Interactions;
using System.Threading;
namespace Exercise1
{
class Exercise3
{
static void Main()
{
IWebDriver webDriver = new ChromeDriver();
webDriver.Navigate().GoToUrl("http://www.asos.com/men/");
webDriver.Manage().Window.Maximize();
webDriver.FindElement(By.XPath(".//input[#data-testid='search-input']")).SendKeys("nike trainers");
webDriver.FindElement(By.XPath(".//button[#data-testid='search-button-inline']")).Click();
WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(5));
IWebElement country = wait.Until(ExpectedConditions.ElementExists(By.CssSelector("article img")));
webDriver.FindElement(By.CssSelector("article img")).Click();
IWebElement Size = webDriver.FindElement(By.XPath(".//select[#data-id='sizeSelect']"));
SelectElementFromDropDown(Size, "UK 10.5 - EU 45.5 - US 11.5");
webDriver.FindElement(By.XPath("//*[#data-bind='text: buttonText']")).Click();
webDriver.FindElement(By.XPath("//a[#data-testid='bagIcon']")).Click();
IWebElement Qty = webDriver.FindElement(By.Id("bagApp"));
SelectElementFromDropDown(Qty, "2");
webDriver.FindElement(By.XPath("//*[#data-bind='click: update']")).Click();
//int trainer = 145;
//while (trainer < 200){
// Console.WriteLine(trainer);
// trainer = trainer * 2;
//}
webDriver.Quit();
}
private static void SelectElementFromDropDown(IWebElement ele, string text)
{
SelectElement select = new SelectElement(ele);
select.SelectByText(text);
}
}
}
You drop down is made of Divs and spans, Select class will not help you in this case.
You can try this code :
IList<IWebElement> options= webDriver.FindElements(By.CssSelector("li[class*='select2-results__option']"));
foreach (IWebElement element in options){
if(element.GetText().Equals("2")){
element.Click();
}
}
Note that before trying to select value from drop down , you have to click on down arrow button for that you can use this code :
webDriver.FindElement(By.CssSelector("span#select2-d2bx-container+span")).Click()
You should use explicit wait as you are moving to new page for this operation.
You can select the webelement as below
//Explicit wait is added to ensure that my bag item section is loaded successfully
WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.ElementExists(By.XPath("//select[contains(#class,'bag-item-quantity')]")));
IWebElement qtyElement = webDriver.FindElement(By.XPath("//select[contains(#class,'bag-item-quantity')]"));
SelectElementFromDropDown(qtyElement,"2");
The error is occurring because you are using the SelectElement class on an HTML element that is not a SELECT, a DIV in this case.
In order to select the desired option, you need to click the dropdown to open it and then click the desired option from the dropdown. Since you will likely be selecting options more than once, it's a good idea to put the code to do that into a function.
public void SelectOption(string s)
{
new WebDriverWait(webDriver, TimeSpan.FromSeconds(5)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector($"span[title='{s}']"))).Click();
}
Then call it like
webDriver.FindElement(By.CssSelector("span.select2")).Click();
SelectOption("2");

How can you automate Firefox from C# application?

Start with the simplest task of capturing the URL in Firefox from a C# application. It appears using user32.dll Windows API functions will not work as is the approach for capturing the URL within IE.
Should I need to do a capture of the URL with AutoHotkey, for example, I would send Ctrl+L (put focus in address bar and highlight content) and Ctrl+C (copy selection to clipboard). Then you just read the clipboard to get the info.
For more complex tasks, I would use Greasemonkey or iMacros extensions, perhaps triggered by similar keyboard shortcuts.
WatiN has support for Firefox.
WebAii can automate FireFox, including setting and retrieving the URL
It appears to be very beta-ey, but someone built a .net connector for mozrepl. Actually, the mozrepl codebase just moved to github. But mozrepl lets you issue commands to the Firefox's XUL environment.
Try Selenium (the Google testing engine - http://seleniumhq.org/) You can record task (Webpages UI related) done in Firefox and the convert the recording into a C# source :)
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, "");
}
}
}
}
One Microsoft tool I ran into:
UI Automation, as part of .NET 3.5
http://msdn.microsoft.com/en-us/library/aa348551.aspx
Here's an example:
http://msdn.microsoft.com/en-us/library/ms771286.aspx
I don't have UI Spy on my pc to interrogate Firefox, so I don't know if this will help out with your user32.dll problem.

Categories