Test below fails, saying that xpath expression is not correct. I did it according to online tutorials.
// open browser
IWebDriver webDriver = new FirefoxDriver();
// navigate to site
webDriver.Navigate().GoToUrl("https://localhost:44311/");
// identify details button
IWebElement detailsLink = webDriver.FindElement(By.XPath("//*[contains(., 'Details')]"));
// operation
detailsLink.Click();
var detailsLabel = webDriver.FindElement(By.XPath("//div[text() = 'Change in $'"));
// assertion
Assert.That(detailsLabel.Displayed);
I want to create simple Selenium test.
I'm pressing specific button to open new page
Checking if specific object is loaded correctly on that page
Button is <a></a> with Details inside. There are actually duplicates of that, the only unique thing is href. This might be the first issue, but I don't know how to "catch" it.
detailsLabel is actually a <div>Change in $</div> with class that I think is irrelevant to the tests.
So, my question is, how to write this test correctly? Test itself should be more or less fine, but detailsLink and detailsLabel has certain issues.
Edit
IWebElement detailsLink = webDriver.FindElement(By.CssSelector("[href*='Details?cryptocurrency=BTC']"));
//operation
detailsLink.Click();
var detailsLabel = webDriver.FindElement(By.XPath("//div[contains(text(),'Change in $')]"));
Return exception Selenium.StaleElementReferenceException for detailsLink
Edit
IWebElement detailsLink = webDriver.FindElement(By.CssSelector("[href*='Details?cryptocurrency=BTC']"));
detailsLink.Click();
var detailsLabel = webDriver.FindElement(By.XPath("//*[text()='Change in $```
Test fails at `detailsLabel`, fails to find our target `div`.
To validate if //*[contains(., 'Details')] xpath is unique you can do something like
List<WebElement>list = webDriver.FindElements(By.XPath("//*[contains(., 'Details')]"));
now, if list is empty - this means your locator is wrong and if it contains more than 1 element your locator is not unique.
But the better way is to validate this manually and directly on the webpage with F12 Inspector tool on your browser.
To locate the element containing some href without the specific href text use //href in case href is an element tag. Otherwise use //*[#href] if href is an attribute.
For the detailsLabel try using //div[contains(text(),'Change in')] xpath
I used Java syntax, but it's similar enough to C#
Related
I'm using Selenium ChromeDriver v2.40, Chrome version 67.
var driver = Browser.GetChromeDriver();
driver.Navigate().GoToUrl(url);
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
var abc=driver.FindElement(By.XPath("//*[#id='pdp-size-select']"));
var aaa=wait.Until(d => d.FindElement(By.XPath("//*[#id='pdp-size-select']")));
abc.Click(); // failed because elementisnotvisible
the above two findelement works fine, can get value but cannot click because the element is not visible
so i go on to try ExpectedConditions, and no luck with this:
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='pdp-size-select']")));
Above code returns:
OpenQA.Selenium.WebDriverTimeoutException: 'Timed out after 10 seconds'
Does it have any backward compatibility issues with Chrome v67?
As per the error elementisnotvisible seems you are pretty close. Moving forward as you are trying to invoke Click() on the element, so instead of ExpectedConditions as ElementIsVisible() you need to use ElementToBeClickable() as follows:
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.XPath("//*[#id='pdp-size-select']"))).Click();
With out any reference to SeleniumExtras and WaitHelpers the line of code will be:
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//*[#id='pdp-size-select']"))).Click();
Note: As you mentioned you are using Chrome v67.x ensure that you are using ChromeDriver v2.40 (but not ChromeDriver v2.4)
Update
Debugging further it seems the Locator Strategy you have adapted, identifies exactly two (2) elements within the HTML DOM. So you need to construct a unique locator to identify and click the desired element as follows:
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//a[#data-track-action='Product-Page']//following::select[#id='pdp-size-select']"))).Click();
Note: The desired element is a select element and if you desire to interect with the <select> element as per best practices you need to use the SelectElement Class from OpenQA.Selenium.Support.UI Namespace.
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.
I'm going to explain this the best I can.
I run tests using the 3 major browsers, firefox, chrome and IE.
I have line where I select data from a drop down menu. Here is an example of what I use.
new SelectElement(CPC_Main.driver.FindElement(By.XPath("//select[#id='orgVdc']"))).SelectByText("Selenium_vDC");
This will select my element orgVdc and select the text value by Selenium_vDC. This will work perfectly for Firefox however it hangs and timesout for Chrome.
From what I can tell the issue is related to the default value of that element.
For example if default value of the element is "Test_vDC" selenium will successfully change it "Selenum_vDC" for all browsers.
However if the default value was "Selenium_vDC" already then Chrome will hang on trying to select that same value.
I hope that explains this enough, in a nut shell Chrome does not like matching default values.
I had encountered issue like this in the past. I used to get exceptions like "The element is no longer attached to the DOM". The issues(stale reference exceptions) like these needs a solid exception handling to make sure Automation execution is not affected.
You can try the below code. You can modify the below code as per your code set up.
public void SetDropDownValue(string Xpath, string value)
{
var element = FindElement(By.Xpath("Xpath"));
var selectElement = new SelectElement(element);
//check whether the option is selectable or not
var wait = new WebDriverWait(this.driver, this.testCaseConfiguration.WaitTime);
wait.Until(ExpectedConditions.TextToBePresentInElement(selectElement , option));
try
{
selectElement.SelectByText(value);
}
catch (StaleElementReferenceException)
{
element = FindElement(By.Xpath("Xpath"));
selectElement = new SelectElement(element);
selectElement.SelectByText(value);
}
}
Setup Details:
Webdriver 2.39
IEDriverServer 2.39
I'm running Selenium automation on an internal site. The code works fine on Firefox 27 but there's an issue on IE8
I'm trying to first clear and enter text in a text field on IE. This fails on IE with the error "Element must not be hidden, disabled or read-only." I checked the element properties on IE and it does indeed show enabled as False, even though the element is plainly available. On Firefox, enabled is correctly set to True.
I've tried to use Xpath and sendkeys but they don't work. Here what I tried:
driver.FindElement(By.XPath("//input[#name='tagName']")).Clear(); - not working
driver.FindElement(By.XPath("//input[#name='tagName']")).SendKeys(tagName); - not working
driver.FindElement(By.Id("tagName")).SendKeys(Keys.Control); - not working
driver.FindElement(By.Id("tagName")).Clear(); - not working
driver.FindElement(By.Id("tagName")).SendKeys(tagName); - not working
Is there some way I can access this element on IE?
Thanks,
J.
We frequently test against IE8 and encounter "unique" Selenium issues.
Sometimes we use ExecuteScript to bypass Selenium's finicky selectors, and use jQuery to return the element or to manipulate it directly:
// Get an element
IWebElement element = (IWebElement) driver.ExecuteScript("return $('#tagName')[0]");
// Clear the value of a field
driver.ExecuteScript("$('input[name=\'tagName\']').val('');");
The best solution was the builder object of Selenium. I used this to force the automation to select the textbox and enter test like so:
IWebElement searchField = Global.driver.FindElement(by);
builder.Click(searchField).SendKeys(searchField, textToEnter).Perform();
This worked!
J.
WebElement searchField = Global.driver.FindElement(by);
builder.Click(searchField).SendKeys(searchField, textToEnter).Perform();
****its working but sending wrong text to the field.
For ex: i have to send "11-12-2015" and it is sending "28-12-2015".
Any Clue what's happening when performing inserting action.****
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