OpenQA.Selenium.NoSuchElementException - c#

class Program
{
static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver();
//Dev environment
driver.Url = /*URL*/;
var trialGroupName = driver.FindElement(By.Name("TrialGroupName"));
trialGroupName.SendKeys(/*trial group name */);
var userName = driver.FindElement(By.Name("UserName"));
userName.SendKeys(/*username*/);
var password = driver.FindElement(By.Name("UserPassword"));
password.SendKeys(/*password*/);
var loginButton = driver.FindElement(By.Id("Ok"));
loginButton.Click();
//Find and click on Browse tab
var browseTab = driver.FindElement(By.Id("17"));
browseTab.Click();
}
}
OpenQA.Selenium.NoSuchElementException: 'no such element: Unable to locate element: {"method":"id","selector":"17"}
(Session info: chrome=58.0.3029.110)
(Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 6.1.7601 SP1 x86_64)'
Here's the inspect information:
<td>
<a id="17" class="defaultMenu initMenu" href="javascript:onMenuHref(17)" notran="">Browse</a>
</td>
I've also tried running it with the XPath (both the short version from Chrome and the long version from FireBug) and I receive the same error. I've tried adding in an implicit wait and a Thread.Sleep() but still received the same error. Also tried starting on a different field and tabbing to it and then it gave me the same exception but on the new field. I also tried playing around with cssSelector this morning and couldn't get that to work either. I did try to do an explicit wait but I'll be honest, I'm still trying to digest and understand it as waits are a new concept and I don't fully understand it, so I don't think I'm doing it right.
I'm a beginner, and I'm currently just trying to write the script to get it to the actual page that needs testing. I've been teaching myself some coding and selenium as I'm the only QA person at my company right now and I really think we could benefit from automation. This portion of the page isn't actually programmed by us it's done by a third party who hosts the system we use so I'm limited to what I see in the inspect.
(I commented out the user login information and URL because it is for internal use only and the page can't be reached outside of our systems anyways. Also I'm pretty sure I'm not allowed to do so by my employer).
Any help on this would be greatly appreciated, or any additional resources I can use. I've been using google mostly so there may be other pages you are aware of that could help me that I haven't found yet.

The login button takes you to a new page, which you need to wait for it to load. Try using an explicit wait to wait for the tab to be clickable. The timeout is 10 seconds in the following example, so modify that as needed.
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement browseTab = wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("17")));

Related

C# Selenium Can't Locate to any Element

Why C# + Selenium can't locate to any element from this URL only
I want to try to filling data to textbox programmatically using c# + selenium.
I had tried for some sites and it worked, but only that site it doesn't work. This is my code.
class Program
{
static void Main(string[] args)
{
Test test = new Test();
test.testDriver();
Console.WriteLine(Environment.NewLine + "Done!");
Console.ReadLine();
}
}
public class Test
{
public void testDriver()
{
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl(#"http://atrium.xsis.co.id/#!/");
IWebElement login = driver.FindElement(By.Name("email")); //Unable to locate element
//IWebElement login = driver.FindElement(By.Id("email")); //Unable to locate element
//IWebElement login = driver.FindElement(By.Name("password")); //Unable to locate element
//IWebElement login = driver.FindElement(By.Id("password")); //Unable to locate element
//IWebElement login = driver.FindElement(By.XPath("//input[#id='password']")); //Unable to locate element
//IWebElement login = driver.FindElement(By.XPath("//input[#id='email']")); //Unable to locate element
//IWebElement login = driver.FindElement(By.XPath("//input[#name='password']")); //Unable to locate element
//IWebElement login = driver.FindElement(By.XPath("//input[#name='email']")); //Unable to locate element
login.SendKeys("MyName");
login.Submit();
//------------------------------Some sites, i have tried
/* --It Worked
driver.Navigate().GoToUrl(#"https://accounts.google.com/");
IWebElement login = driver.FindElement(By.Name("identifier"));
login.SendKeys("MyName");
login.Submit();
*/
/* --It Worked
driver.Navigate().GoToUrl(#"https://web.facebook.com/");
IWebElement login = driver.FindElement(By.Name("email"));
login.SendKeys("MyName");
login.Submit();
*/
/* --It Worked
driver.Navigate().GoToUrl(#"https://stackoverflow.com/");
IWebElement login = driver.FindElement(By.Name("display-name"));
login.SendKeys("MyName");
login.Submit();
*/
/* --It Worked
driver.Navigate().GoToUrl(#"https://github.com/login?");
IWebElement login = driver.FindElement(By.Name("login"));
login.SendKeys("MyName");
login.Submit();
*/
}
}
I think that is simple code, just locate specific element. Or use other method if the web using IFrame, but there is no frame.
I am using vs 2013 community edition, WebDriver.dll version 3.4.0.0, RunTime version v4.0.30319., and Firefox 54.0.1 (32-bit).
There's something which is kind of cool and annoying at sometime in Selenium, it literally try to work exactly as if the user where using the browser. Hence you gotta be sure that the element exposed on your screen and the user can click on it, otherwise you must scrool until it.
Another important thing is the bootstrap, which sometimes change the visibility of its elements and replace to others.
Scrool to elements on page's bottom.
Guarantee the element is literally visible.
Check whether there's something over the element.
I can't comment yet and I'd prefer that this be a comment, but here goes anyway.
I tried browsing to the site you reference and can't get there. Not sure if it's live or not or just blocked by my company's firewall. I really wanted to look at the code for the site because I've seen issues like this before. Typically when I've seen this it's either a locater issue or an iframe issue. If you could post the html from the site that would help diagnose your issue. Oh, and the code you have written looks correct, but that doesn't help if Selenium is looking in the wrong frame.
So, here's what I would try.
First, I'd use FireFox's developer version and inspect the element. Make sure it's not inside of a frame that you haven't noticed.
Second, I'd try to locate by CSSSelector. I know that it should work by Id or XPath, but sometimes it doesn't and I don't know why. However, I have had luck with locating by CSSSelector when the others fail. You can copy the CSS Selector directly out of the inspection window in FireFox's developer version.
Third, if none of that works, I'd pass a SwitchTo the Default Content Frame, just in case the entire page is in a frame that is buried inside a div that you're missing. The code for that is:
driver.SwitchTo().DefaultContent();
Finally, the last thing I would try is adding some explicit waits just in case there is an element loading after you are trying to access it. Unfortunately this happens more than I'd like.
This would be my final, kitchen sink, approach.
Thread.Sleep(2000);
driver.SwitchTo().DefaultContent();
Thread.Sleep(2000);
By emailLocator = By.CSSSelector("insert CSS Selector Here");
IWebElement email = driver.FindElement(emailLocator);
email.SendKeys("email address");
If that still doesn't work, please post the html for the page you're trying to access and we'll see if we can figure out why it's failing to locate the element.
Your code looks good... something simple like your first attempt, By.Id("email"), should have worked. When it doesn't you want to look first to see if the desired element is in an IFRAME. In this case, it isn't.
The next thing you should try is an explicit wait, WebDriverWait.
IWebElement email = new WebDriverWait(Driver, TimeSpan.FromSeconds(3)).Until(ExpectedConditions.ElementIsVisible(By.Id("email")));
email.SendKeys("MyName");
email.Submit();
The wait.Until() returns the element waited for so you can capture that by assigning the return to a variable and then using it, as I did above.
Have you tried using Xpath?
driver.findElement(By.xpath("//input[#name='email']"))
I find that sometimes Selenium is finicky and you need to try other approaches to find elements.

How to maintain browser state between invocations under Selenium and Firefox?

Context: Microsoft Azure VM; VS2015 Community; C#; Selenium.WebDriver.2.52.0; Firefox 44.0.2; Console (i.e. not running under IIS)
How is state maintained under Firefox using Selenium. Programmatically I go to one page, enter login details, and traverse to a second domain. Then I close the browser, re-open and try to go to a link on the second domain. I end up at the login page again being requested for login details.
When doing this interactively, the browser remembers that I logged in on the first page and automagically transports me the second domain's page.
I have set up a webserver profile in C:\Users\Bruce\AppData\Roaming\Mozilla\Firefox\profiles.ini as
[General]
StartWithLastProfile=1
[Profile0]
Name=default
IsRelative=1
Path=Profiles/eracklz4.default
[Profile1]
Name=webserver
IsRelative=1
Path=Profiles/webserver.default
Default=1
So one would think that even if I didn't explicitly state that I wanted to use the webserver profile, nevertheless, it would choose that profile and work with it. Just in case I go on to state it explicitly
var seleniumProxy = new Proxy();
seleniumProxy.HttpProxy = "localhost:" + port; // port provided by BrowserMob Proxy
...
FirefoxBinary fb = new FirefoxBinary(#" C:\Program Files (x86)\Mozilla Firefox\firefox.exe");
FirefoxProfileManager fpm = new FirefoxProfileManager();
FirefoxProfile fp = fpm.GetProfile("webserver");
fp.DeleteAfterUse = false;
fp.SetProxyPreferences(seleniumProxy);
IWebDriver wd = null;
try
{
wd = new FirefoxDriver(fb, fp);
}
catch (Exception exc)
{
System.Diagnostics.Debug.Print(exc.Message);
}
IJavaScriptExecutor js = wd as IJavaScriptExecutor;
ExistingProfiles in the FirefoxProfileManager lists webserver so the fpm var is not null.
At this point, I'm getting pretty confident that the session's data will be persisted, because when I look at fpm in the debugger, Non-Public members -> profiles -> [1] -> Value is given as "C:\\Users\\Bruce\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles/webserver.default".
Having transferred the profile data from fpm to fp, with the .GetProfile method, the ProfileDirectory property of fp reads as null, Non-Public members -> profileDir is also null and Non-Public members -> sourceProfileDir is "C:\\Users\\Bruce\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles/webserver.default"
By rights, therefore, one should expect passwords to be persisted to the webserver profile, especially when one explicitly saves data to the profile with regular calls to fp.WriteToDisk();.
However! The last time I ran the code, I got a anonymous.359f853715d5418c87c7393c629dcb1a.webdriver-profile in C:\Users\Bruce\AppData\Local\Temp
Granted, there did appear to be some activity in the Roaming profile. However, the password for the login page was not persisted.
What's happening here? Is session data persistable in Selenium + Firefox, or was there a design decision somewhere that no matter how you specified it, no state would be saved? Am I wanting to do something that is intrinsically forbidden?
NEXT DAY
Added the following code after reading a StackOverflow posting from 2014 discussing similar issues. However, I'm still seeing a temporary profile being created in AppData\Local\Temp. And no changes were made to the Roaming profile. Problem not solved.
A LITTLE LATER
Am currently experimenting with Google Chrome instead of Firefox, viz
ChromeOptions co = new ChromeOptions();
string tfn = #"C:\Temp";
co.AddArgument("user-data-dir=" + tfn);
co.Proxy = seleniumProxy;
IWebDriver wd = new ChromeDriver(co);
I'm not very confident that this will make much difference. Notably, I can't figure out how to set or get the name of the profile folder created in Temp. The above code creates a Default folder, but there's no mention of that in the properties view in VS2015C.
FINALLY
Surprise, surprise, that actually worked. Bye bye Firefox. Hello Google Chrome. Seems there's enough session data stored to make the traversal to the second site feasible. Will probably change the directory away from Temp and have it client-specific. Kudos to the folk at ActiveState Python.

How to workaround certain differences between PhantomJSDriver and ChromeDriver

I have an issue when switching from ChromeDriver to PhantomJSWebDriver, that I need a workaround for.
Using the ChromeDriver I perform a .Click on a visible element, with another visible element next to it. the .Click makes the web page place a 'popup' over these elements. I then perform a .Click on an element within this 'popup' and it then goes away, and I am able to perform a .Click on the second of the original elements and it all works fine.
However, when I switch to using the PhantomJSDriver it complains that the second element is NOT visible after the 'popup' has been removed, and so wont do the .Click.
Is this a known issue with the PhantomJS driver, or is there some way to get it to 're-evaluate' what is visible? I have tried using a DriverWait looking for the element and waiting for it to be 'Displayed' but that doesn't work
WebDriverWait waitforpopdown = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
waitforpopdown.Until(d => {
var elpd = driver.FindElement(By.ClassName(trid));
return elpd.Displayed;
});
I'm using PhantomJS 2.1.1 and Selenium 2.52.0.0 and using C#
I had the same problem with PhantomJSDriver. It hasn't the same javascript engine than Chrome, FF and IE.
I "fixed" my problem by installing a selenium server that is running chrome on a docker. If you have the ability to do that, I would recommend to work that way. It's an actual chrome browser that is running, so you don't have any difference between your different types of chromes.
You can find information about it on the following page : https://github.com/peroumal1/docker-chrome-selenium
EDIT : You have to declare your driver like this (note that it's java Syntax, but I'm sure you'll be able to find the C# syntax) :
return new RemoteWebDriver(new URL("http://myurl.url:8888"), DesiredCapabilities.chrome());

Inconsistent behaviour of Click() in Selenium

I'm working on a Product automation(Web CMS), where element.Click() shows the inconsistent behaviour. Basically we are using,
Selenium + Nunit GUI(unit testing framework) - To run the test cases from local on a particular environment
Selenium + Asp.net web application - Multiple user's can run the test cases on different environment
Here environment I mean different levels(Dev, SIT, QA, Production).
My Concern
In one of my test cases, I want to Click a button. So for that, I have tried few code. But all are inconsistent behaviour. Here Inconsistent I mean, the code whatever I wrote for clicking a button are only working in my local or server and viceversa.
1st attempt:-
I tried all the element locator's
IWebElement element = driver.FindElement(By.Id("element id goes here"))
Working fine at my local, but not in server
Result - Failed
2nd attempt:-
driver.FindElement(By.XPath("Element XPath goes here")).SendKeys(Keys.Enter);
Working fine at server, but not in local
Result - Failed
3rd attempt:-
IWebElement element = driver.findElement(By.id("something"));
IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
executor.ExecuteScript("arguments[0].click()", element);
Not working in both(local and server)
Result - Failed
At last, I tried waiting for the element to be visible and performing action
4th attempt:-
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
return wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("element xpath goes here")));
After webdriver wait performing action on that element (element.click())
Working fine at local but not in server
Result - Failed
I'm looking for a solution, where Clicking the button should not be an inconsistent behaviour. Basically it should work fine in both (Local and Server). Your help would be greatly appreciated..Thanks in advance
FYI - I'm testing in Mozilla Firefox browser 38.5.2
I'm using Selenium in C# locally on Win7 and remotely on Win10 and MacOS with the Firefox browser and also noticed that Firefox sometimes requires special treatment for IWebElement.Click(). So I wrote myself an extension method, which works fine for me, no matter by what locator the element was found:
public static void Click(this IWebElement element, TestTarget target)
{
if (target.IsFirefox)
{
var actions = new Actions(target.Driver);
actions.MoveToElement(element);
// special workaround for the FirefoxDriver
// otherwise sometimes Exception: "Cannot press more then one button or an already pressed button"
target.Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.Zero);
// temporarily disable implicit wait
actions.Release().Build().Perform();
target.Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(MyDefaultTimeoutInSeconds));
Thread.Sleep(500);
actions.MoveToElement(element);
actions.Click().Build().Perform();
}
else
{
element.Click();
}
}
If you want more stable behavior for your test cases, I would recommend using ChromeDriver. It never needs any special treatment at all, and it's also much faster than the FirefoxDriver.

Selenium chrome driver click() method not always clicking on elements

I am writing integration tests in c# and when I use the click() method on certain elements inside a dialog box nothing happens and I get no errors. It will click some of the elements inside the dialog but not others. I thought if it wasn't selecting them properly then it would throw and exception but it runs smooth and says test passed even though it never actually clicked the button. The dialog box is an iframe.
I thought maybe it was trying to click a button that wasn't display yet or enabled so I added this before the click() call:
_driver.SwitchTo().Frame(_frameElement);
_wait.Until(d =>
{
var shippingInfoButton = d.FindElement(By.CssSelector("input[title ='Info']"));
return shippingInfoButton.Displayed && shippingInfoButton.Enabled;
});
var infoButton = _driver.FindElement(By.CssSelector("input[title ='Info']"));
ScrollToElement(infoButton);
infoButton.Click();
again this runs with no thrown exceptions so I'm assuming it has found the element and it is both displayed and enabled.
Let me know if you need any more info. Thanks
I can't explain why the selenium driver .click() method won't fire on some elements in the page but not others, but I did find a solution.
Using IJavaScriptExecutor you can click the element using javascript instead and in my case it worked.
Here is the code to run the IJavaScriptExecutor and below is my whole method.
//IJavaScriptExecutor
IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].click();", infoButton);
//my whole method for clicking the button and returning the page object
public ShippingMethodDetailsPageObject SelectShippingMethodInfo()
{
_driver.SwitchTo().Frame(_frameElement);
_wait.Until(d =>
{
var shippingInfoButton = d.FindElement(By.CssSelector("input[title='Info']"));
return shippingInfoButton.Displayed && shippingInfoButton.Enabled;
});
var infoButton = _driver.FindElement(By.CssSelector("input[title ='Info']"));
IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].click();", infoButton);
_driver.SwitchTo().DefaultContent();
return new ShippingMethodDetailsPageObject(_driver, false);
}
I ran into a similar problem. If it's the same problem there's a fault in the ChromeDriver it can't click certain elements because of surrounding divs etc. Bit lame really.
A simple fix is to send the Enter key e.g. element.SendKeys(Keys.Enter). Seems to work across all browsers.
I have some tests that works in Firefox all the times, and in Chrome it drove me mad, because sometimes it passed successfully, and sometimes the ".click" didn't work and it would fail the test.
Took a long time to notice it, but the reason was: I used to sometimes minimize the browser to 80% to be able to see the browser along side my IDE. it appears that the ".click" doesn't work when I did it.
At least for me this was the issue

Categories