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

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");

Related

C# FindElement(By...) with two criteria

I am currently trying to automate a checkout process. Now I am stuck, the buttons on the site displaying the sizes are nearly identical, they only differ in value
That's why I wanted to ask if I can differ them by two criteria like class + value.
Code:
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace selenium1
{
class MainClass
{
public static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://www.off---white.com/en-de/shopping/off-white-odsy-1000-sneakers-14760681");
IWebElement element = driver.FindElement(By.());
element.Click();
}
}
}
Thank you in advance for your help!
you could use a CSS selector.
for example: css = element_name[<attribute_name>='<value>']
So in your case it would be:
IWebElement element1 = driver.FindElement(By.CssSelector("input[value='25']")
IWebElement element2 = driver.FindElement(By.CssSelector("input[value='27']")
This article should help
You are right. You can club up the value attribute along with any other attribute e.g. data-test, to construct the locators which would identify the element uniquely within the DOM Tree.
To click() on the element with text as 39 you need to induce WebDriverWait for the desired ElementToBeClickable() and you can use either of the following Locator Strategies:
Using CssSelector:
driver.Navigate().GoToUrl("https://www.off---white.com/en-de/shopping/off-white-odsy-1000-sneakers-14760681");
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("input[data-test='sizeSelector'][value='23']"))).Click();
Using XPath:
driver.Navigate().GoToUrl("https://www.off---white.com/en-de/shopping/off-white-odsy-1000-sneakers-14760681");
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//input[#data-test='sizeSelector' and #value='23']"))).Click();

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();
}
}

Using XPaths within a Loop C#

I currently have a piece of code that adds items into a bag with a 200 limit. But instead of having this limit in place i want to introduce a loop which will keep adding items until 200 is reached.
The issue i'm having is i'm not sure how i'd incorporate XPaths within my loop
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 Mock1
{
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(10));
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 - EU 45 - US 11");
webDriver.FindElement(By.XPath("//*[#data-bind='text: buttonText']")).Click();
wait.Until(ExpectedConditions.ElementExists(By.XPath("//span[text()='Added']")));
webDriver.FindElement(By.XPath("//a[#data-testid='bagIcon']")).Click();
// I want to introduce a loop from here so that when item is added to the bag it keeps looping till 200 is reached.
wait.Until(ExpectedConditions.ElementExists(By.XPath("//select[contains(#class,'bag-item-quantity')]")));
string totalPrice = webDriver.FindElement(By.XPath("//span[#class='bag-subtotal-price']")).Text;
double pricePerItem = Convert.ToDouble(totalPrice.Substring(1));
int priceLimit = 200;
double noOfQuantity = priceLimit / pricePerItem;
IWebElement qty = webDriver.FindElement(By.XPath("//select[contains(#class,'bag-item-quantity')]"));
SelectElementFromDropDown(qty, Math.Floor(noOfQuantity).ToString());
wait.Until(ExpectedConditions.ElementExists(By.XPath("//button[#class='bag-item-edit-update']")));
webDriver.FindElement(By.XPath("//button[#class='bag-item-edit-update']")).Click();
// webDriver.Quit();
}
private static void SelectElementFromDropDown(IWebElement ele, string text)
{
SelectElement select = new SelectElement(ele);
select.SelectByText(text);
}
}
}
If I have understood your question properly, You want to use loop to add items until 200 limit is reached. In this case, you can simply adapt your code something like this
Assuming below line (first line) returns you total price:
string totalPrice = webDriver.FindElement(By.XPath("//span[#class='bag-subtotal-price']")).Text;
double total = Convert.ToDouble(totalPrice)
while(total > 200)
{
//code for adding items.
//update total price
total = Convert.ToDouble(webDriver.FindElement(By.XPath("//span[#class='bag-subtotal-price']")).Text);
}

Selenium C# Can't find ID or Title

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();

Select element issue - webdriver - c#

I'm getting the below error while running in NUnit,
I'm finding an element and storing it in a variable, and while trying to select the element, i'm getting the error. Tried using in this way
IWebElement fromitem = WebDriver.FindElement(By.Id("from")); but same error persists.
Is there any way i can select the element?
Note : I verified the element id with firebug, there seems to be no problem with it.
The code below,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.Events;
using OpenQA.Selenium.Support.PageObjects;
namespace SeleniumTests
{
[TestFixture]
public class Sel
{
public static IWebDriver WebDriver;
private String baseURL;
[SetUp]
public void SetupTest()
{
WebDriver = new FirefoxDriver();
baseURL = "http://www.x-rates.com/calculator.html";
}
[TearDown]
public void TeardownTest()
{
WebDriver.Quit();
}
[Test]
public void newtest()
{
WebDriver.Navigate().GoToUrl(baseURL + "/");
var fromitem = WebDriver.FindElement(By.Id("from"));
var toitem = WebDriver.FindElement(By.Id("to"));
var fromval = new SelectElement(fromitem); //Error occurs
var toval = new SelectElement(toitem);
fromval.SelectByText("USD - US Dollar");
toval.SelectByText("INR - Indian Rupee");
WebDriver.FindElement(By.LinkText("Currency Calculator")).Click();
var curval = WebDriver.FindElement(By.CssSelector("span.ccOutputRslt")).GetAttribute("Value");
var expectedValue = 61.456825;
Thread.Sleep(900);
Assert.AreEqual(expectedValue, curval.Trim());
}
}
}
The SelectElement class can only be used with actual HTML <select> elements. In the page you provided, the element in question is an <input> element, with functionality added through CSS and JavaScript to enable it to act like a drop-down list. As such, attempting to use it with the SelectElement class will throw an exception indicating that the element is not of the correct type.
The "File does not exist" error message is a red herring. It's only there because NUnit is trying to show you the line of source code where the exception is thrown, which is a part of the WebDriver source code. The exception thrown by that line of code should be displayed somewhere within NUnit, which should contain the appropriate informational message.

Categories