Cannot Find Element in Selenium C# - c#

I am trying to locate a dropdown menu button from the following website:
Inspect Element snippet of 'CRO Dashboard DropDown Menu'
My aim is to locate the dropdown button element and click it to open the menu to then continue other operations on it.
The following error occurs when trying to locate the dropdown menu button by id:
OpenQA.Selenium.NoSuchElementException: 'no such element: Unable to locate element: {"method":"css selector","selector":"#dashboardSelectorLink"}
Referring to the image, from the highlighted part I tried to use various locators like finding element by id, css selector, class names, and even xpath but still the program could not locate it so that I can click the element.
Here is some of the code I tried:
dropdown = FindElementByCSS(dropdown, ".ms-crm-ImageStrip-Dropdown_Arrow");
dropdown = FindElementByXPath(dropdown, "//a[#id='dashboardSelectorLink']/span[2]/img");
dropdown = driver.FindElement(By.CssSelector("a[id=\"dashboardSelectorLink\"]"));
dropdown = FindElementByID(dropdown, "dashboardSelectorLink");
dropdown = FindElementByXPath(dropdown, "//cssclass[#id='dashboardSelectorLink']");
dropdown = FindElementByCSS(dropdown, "cssclass[id = 'dashboardSelectorLink']");
dropdown = FindElementByID(dropdown, "dashboardSelectorLink");
dropdown = FindElementByClass(dropdown, "cssclass[id= 'dashboardSelectorLink']");
dropdown = FindElementByID(dropdown, "dashboardSelectorContainer");
The variable 'dropdown' is of IWebElement type and I am using a chrome driver for Selenium C#.
For context, the code is in the following function:
public void EnterDashboardArea()
{
IWebElement navbtn = null;
IWebElement category = null;
IWebElement dropdown = null;
navbtn = FindElementByID(navbtn, "Tab1");
ClickElement(navbtn);
category = FindElementByID(category, "MNG");
ClickElement(category);
Thread.Sleep(5000); //pausing the program so the page fully loads and all elements appear
dropdown = driver.FindElement(By.CssSelector("img[class='ms-crm-ImageStrip-Dropdown_Arrow']"));
ClickElement(dropdown);
}
In the function EnterDashboardArea(), the web elements initially are set to none where they are then filled by the functions 'FindElementByX' as they return an element value.
The functions 'FindElementByX' are created by myself, one e.g. is:
public IWebElement FindElementByID(IWebElement ele, string id) {
ele = driver.FindElement(By.Id(id));
return ele;
}
I even tried installing the selenium chrome extension in order to locate the target exactly but still no success.
What can I do please? - Thanks

Could it be that you are trying to retrieve the element before the element has been loaded into the DOM? Try to set a timeout before reading the element.
Also: is the element contained within a container that is initially hidden, before you open it? Maybe you have to click some button that shows the container and the target element within, before trying to read the element.

Related

Unable to locate an element implemented as <td> using Selenium Web Driver

I wanted to locate the value of BNK1 using Selenium web driver by C#. my local website i found have 2 iframe. i have try to change to get my iframe to change to detail frame for me to get my value of BNK1 in the table.
I had no idea what going on with the problem that i not able locate the iframe by using XPath.
but i having error "no such element: Unable to locate element: {"method":"xpath","selector":"//iframe[#class='tabcontentiframe']"}
IWebElement detailFrame = driver.FindElement(By.XPath("//iframe[#class='tabcontentiframe']"));
driver.SwitchTo().Frame(detailFrame);
IWebElement element = driver.FindElement(By.XPath("//table/tbody/tr/td[contains(text(),'BNK1')]"));
String text = element.Text;
First, let's get sure that your page is fully loaded before trying anything, using a heavy-hand approach,
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
Second, assuming the element you want to access is inside an iframe, you first need to switch to it. Actually, you mention in comment that you have two nested iframes,
// Let's switch to the parent frame
IWebElement tabcontentiframe = driver.FindElement(By.XPath("//iframe[#class='tabcontentiframe']"));
driver.SwitchTo().Frame(tabcontentiframe);
// Let's switch to the child frame
IWebElement iframeHome = driver.FindElement(By.XPath("//iframe[#id='iframeHome']"));
driver.SwitchTo().Frame(iframeHome);
Now, you can do
IWebElement element = driver.FindElement(By.XPath("//table/tbody/tr/td[contains(text(),'BNK1')]"));
// or By.XPath("//td[contains(text(),'BNK1')]")
// or By.XPath("//td[text()='BNK1']")
When you are done, you may want to switch back to the main frame,
driver.SwitchTo().DefaultContent();
You can find the element by using the relative xpath:
IWebElement element = driver.FindElement(By.XPath("//td[text()='BNK1']"));

Selenium C# 'OpenQA.Selenium.ElementNotVisibleException' error

I am trying to access a radio button. From my research I found the element using the name, since the elements of a radio button have the same name. I want to select the second button, but I get an element not visible exception and the location property of the element returned is outside the window. However, I can see the element on the page.
The exception: An exception of type 'OpenQA.Selenium.ElementNotVisibleException' occurred in WebDriver.dll but was not handled in user code
ReadOnlyCollection<IWebElement> webElements = webElement.FindElements(By.Name("thename"));
webElements[1].SendKeys(Keys.Return);
I tried to move to location using the execute javascript as well as the Actions method. Neither worked.
I tried all possible keys to send to click for the Actions method:
Actions actions = new Actions(webDriver);
actions.MoveToElement(webElements[1]);
actions.SendKeys(Keys.Return);
actions.SendKeys(Keys.Enter);
actions.SendKeys(Keys.ArrowDown);
actions.Click();
actions.Perform();
For the javascript executor I tried two methods. To scroll into view, and to scroll by the amount that the Location property of webElement[1] told me it was off by.
IJavaScriptExecutor js = webDriver as IJavaScriptExecutor;
string title = (string)js.ExecuteScript("arguments[0].scrollIntoView(true);", webElements[1]);
string title1 = (string)js.ExecuteScript("javascript:window.scrollBy(557329,136);");
I still keep getting the location not visible exception.
A quick check you could do is open the developer tools in browser and in the console see if document.querySelector("[name='thename']") finds the element. If not, maybe that element is in an iframe or the name you are using may have a typo. You will also want to make sure that the radio button you are trying to access is below 'webElement' in the DOM tree. It's also possible that the page is still loading when you are checking for the element. To check for this put in a wait before trying to find the element so the page can load fully.

Selenium Webdriver: Selecting menu item in multi-level menu

Selenium WebDriver in Visual Studio With C#.
I've create a driver Object, which I'm using an instance of.
I'm trying to Access the top menu on this site: http://store.demoqa.com/
The second menu element, "Product Category", has a submenu. I'm trying to emulate a mouse-over of the "Product Category" element, then select and click the first element in the list (Accessories).
This is what I've got so far, pieced together by several searches here and elsewhere. It works up the point of clicking on the menu item ("Accessories"). I see that the top element is selected, and that the menu item is "selected" because it slightly indents when hovering the mouse over it. However, from there I cannot seem to Click() it.
"menu-item-33" is the top menu item, Product Category.
"menu-item-34" is the sub menu item Accessories.
Actions action = new Actions(FFDriver.Instance);
IWebElement we = FFDriver.Instance.FindElement(By.Id("menu-item-33"));
action.MoveToElement(we).MoveToElement(FFDriver.Instance.FindElement(By.Id("menu-item-34"))).Click().Build().Perform();
It moves to the correct item, but the Click() function doesn't seem to work, since the page isn't changed.
Pardon me if this is too little information, but I've tried to keep it narrowed down to the code that seems to be the struggle.
I do not see why the code you have wouldn't work. However, you can try implementing some explicit wait if necessary. I have tried the following and it works. Note: I always suggest you to use id for locating element. But, I thought I show you another option and directly finding the anchor will be wiser for submenu item
By byId = By.Id("menu-item-33");
By css = By.CssSelector("a[href*='product-category/accessories']");
Actions action = new Actions(_driver);
IWebElement we = _driver.FindElement(byId);
action.MoveToElement(we).Build().Perform();
new WebDriverWait(_driver,TimeSpan.FromSeconds(2)).Until(ExpectedConditions.ElementIsVisible(css)).Click();

How to change the visibility of the button got by Xpath in Selenium

Hello I am working in Selenium Automation testing with Nunit. I have one grid which have bulk of users and there is one remove button on each row of the grid. But that Remove button is visible only on mouse hover. So when I run the script, It gives me the error -
Element is not currently visible and so may not be interacted with
The Xpath of button is
"//div[1]/div[2]/div/section/div[2]/div[contains(.,'IE8 john
smith')]/div/div[2]/button[1]"
I tried working with the actions in selenium but still it gives me the same error.
Actions actions = new Actions(Driver);
var element = Driver.FindElement(By.XPath("//div[1]/div[2]/div/section/div[2]/div[contains(.,'" + fullName + "')]/div/div[2]/button[1]"));
actions.MoveToElement(element);
actions.Click();
actions.Perform();
Can anyone help me out ?
I think the following procedure will help
using Actions, hover over the element step
insert an implicit wait till the element is visible
click the button
Try to force element to be visible using JS:
IWebElement element = driver.FindElement();
js.ExecuteScript("arguments[0].style.visibility = 'visible', arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0].style.opacity = 1", element);
element.Click();

How to handle StaleElementReferenceException when verifying a text?

I have a set of common methods which I run for each test. Like I need to add a few items in my cart and the whole test runs for each item. But for the first item it runs fine and when the process is repeated for the second item it fails while verifying a text and I get a StaleElementReferenceException.
How do I look up the item again or solve this ? Thanks.
Code where it fails:
public bool VerifyItemPresentInCart()
{
//Get the cartsize and verify if one item present
IWebElement cartSize = driver.FindElement(By.CssSelector("div[class='cart-size']>div"));
string actualMsg = cartSize.Text;
string expectedMsg = "1";
VerifyIfTextPresentMethod(expectedMsg,actualMsg);
return true;
}
Error at
IWebElement cartSize = driver.FindElement(By.CssSelector("div[class='cart-size']>div"));
Update: html code
<a class="header-button show-cart has-cart-items" data-view-name="cart-badge" data-view-cid="view5" data-model-cid="c6" data-tappable="true">
Cart
<div class="cart-size">
<div>3</div>
</div>
New code:
IWebElement cardDetails = driver.FindElement(By.CssSelector("div[class='form-field clear-fix']>label[for='cardNumber']>div"));
I would try joining your lines of code:
IWebElement cartSize = driver.FindElement(By.CssSelector("div[class='cart-size']>div"));
string actualMsg = cartSize.Text;
So that they are:
string actualMsg = driver.FindElement(By.CssSelector("div[class='cart-size']>div")).Text;
This means that the text will be retrieved on the element as it is selected. I am wondering if between getting a handle on the element via its parent and retrieving the text you are losing focus on that element. Alternatively, remove the >div from your css and see if it retrieves the text anyway.
This not working suggests the situation you are facing is the point under the title The Element is not Attached to the DOM. The fact that your target text is within only divs suggests that this area is being styled by javascript and thus may only be active at certain times. If this element is not active, but is accessible, you can still receive the StaleElementReferenceException, as indicated at that page. Your next step would be to see if you can click a parenting div to activate this target div prior to accessing its text (eg. make sure the element is attached to the DOM then call the code you have provided).

Categories