I want to click a dropdown element. I have mentioned element's xpath/css both. But it is constantly giving error "no element found". I am working on C# on selenium . I have also given dropdown ID first then wait for the dropdown element and then get it clicked but it gives same error always. Any idea ???
It depend of available iFrame or maybe you should switch to default content. It's complicated, without your code.
Any way try this code. It's working for me:
private static void ChooseZipCode(IWebDriver wd)
{
if (!wd.FindElement(By.XPath("//td[#id='divShipStateCombo']/select//option[3]")).Selected)
{
wd.FindElement(By.XPath("//td[#id='divShipStateCombo']/select//option[3]")).Click();
}
}
// where is "[3]" the position your element(ID) in drop down menu
// or
private static void SelectElement(IWebDriver wd, string CardType)
{
SelectElement cardSelect = newSelectElement(wd.FindElement(By.Name("CardType")));
cardSelect.SelectByText("Visa Card");
}
Related
Below is my current code for my winforms app. Here the user will click the button and then the system will land on a specific index to an array and then print to the text box the contents of that index in the array. The "if" statement is where I am trying to match a specific background image to the specific index. Below in my test "if" statement I am trying to match a specific image in my resource file but I can't seem to figure out what to set the bool to match. I have tried "if(Map_Text="Woods")" which I get CS0029 error. Any tips or online guides I can review?(I apologize if I mis-said anything I am new to coding)
private void button1_Click(object sender, EventArgs e)
{
int start1 = random.Next(0, Map_Array.Length);
Map_Text.Text = Map_Array[start1];
if(Map_Text = "Woods")
{
this.BackgroundImage = Properties.Resources.Woods;
}
}
In your if statement, you're attempting to assign the string "Woods" to Map_Name, which is the reason you're getting CS0029 (which means that the compiler can't implicitly convert the two types.)
Additionally, you'd need to check the Text property of Map_Name instead of checking Map_Name directly, as you're assigning the result of your random selection to that property above your if statement.
if (Map_Text.Text == "Woods") {
this.BackgroundImage = Properties.Resources.Woods;
}
I'm currently creating automatic tests for an application form which I'm using selenium in combination with Specflow.
In my Specflow scenario I have an scenario outline with a few examples that I wish to use. I have no problem populating simple text fields with values from the example in the scenario outline but I can't seem to get selenium to select the same item from the drop down list as I have in my specflow scenario outline.
Specflow scenario outline step
Specflow scenario outline example data
Sending the data from the example
Cathing and populating the text field
How would I duplicate this but instead of populating a text field I want to select an item in a drop down list that is the same as the value in the specflow scenario outline?
Currently I have the step and the example created but I don't know how to correctly send the data and catch and click on the correct item in the dropdown list
Specflow scenario outline step for dropdown
Specflow scenario outline example data for drop down items
EDIT 1:
Current code I have tried for the layer and steps page
Successfully clicks the dropdown but does not choose the same value as in the feature outline
public string MaritalStatus
{
set
{
_driver.FindElement(By.Id("mainApplicant.maritalStatus")).Click();
_driver.FindElement(By.XPath("//ul[#class='dropdown-menu show']//li[#role='presentation']//a[#class='dropdown-item']")).SendKeys(value);
}
}
[Then(#"I choose value (.*) in dropdown MainApplicantMaritalStatus and Check Value")]
public void ThenIChooseValueInDropdownMainApplicantMaritalStatusAndCheckValue(string value)
{
_cashLoanPage.MaritalStatus = value;
}
Successfully clicks the dropdown but only selects the first item in the dropdownlist
public void MaritalStatus1()
{
_driver.FindElement(By.Id("mainApplicant.maritalStatus")).Click();
_driver.FindElement(By.XPath("//ul[#class='dropdown-menu show']//li[#role='presentation']//a[#class='dropdown-item']")).Click();
}
[Then(#"I choose value (.*) in dropdown MainApplicantMaritalStatus and Check Value")]
public void ThenIChooseValueInDropdownMainApplicantMaritalStatusAndCheckValue1(string x)
{
_cashLoanPage.MaritalStatus1();
}
EDIT 2:
With the help from Dazed this code works as intended incase anyone ever stumbles on a similar problem
public void MaritalStatus(string value)
{
_driver.FindElement(By.Id("mainApplicant.maritalStatus")).Click();
_driver.FindElement(By.XPath(string.Format("//ul[#class='dropdown-menu show']//li[#role='presentation']//a[text()='{0}']", value))).Click();
}
I typically use string format for this. I am not sure what your html markup looks like but this will take the "value" you pass in from the scenario outline and replace it in your locator type, xpath in this instance.
[Then(#"I choose (.*) in dropdown MainApplicantMaritalStatus and Check value")]
public void IChooseInDropdownMainApplicantMaritalStatusAndCheckValue(string value)
{
driver.FindElement(By.XPath(string.Format("//select[#id='status']/option[text()='{0}']",
value))).Click();
}
****Update***
go here https://www.w3schools.com/html/tryit.asp?filename=tryhtml_elem_select if you look at an xpath of
//select[#name='cars']/option ---- you get 4 results
If I add this
//select[#name='cars']/option[contains(text(), 'Saab')] -- you get one result
If I change the path in my code to this, I can pass in the value I want to select.
string value = "Saab";
driver.FindElement(By.XPath(string.Format("//select[#name='cars']/option[contains(text(), '{0}')]", value))).Click();
so using your code, it looks like you are using POM? You could add this to the page as a method, and call it from the step. Since we can't see your full html though, I can give you the exact xpath for the drop down value.
from steps:
string myValue = "Married"
Pages.MyPage.SetMaritalStatus(string myValue);
from Pages:
public void SetMaritalStatus(string value)
{
_driver.FindElement(By.Id("mainApplicant.maritalStatus")).Click();
_driver.FindElement(By.XPath(string.Format("//ul[#class='dropdown-menu show']//li[#role='presentation']//a[#class='dropdown-item']/option[text()='{0}']", value))).Click();
}
Here is the approach that should work.
[Then(#"I choose (.*) in dropdown MainApplicantMaritalStatus and Check value")]
public void IChooseInDropdownMainApplicantMaritalStatusAndCheckValue(string status)
{
// lets say you have select element
WebElement maritalStatus = driver.findElement();
WebElement option = maritalStatus.findElement(By.xpath("./option[normalize-space(.)='" + status + "']"));
// click on option
option.click();
}
I want to click on specific element, but this element is not displayed in current view, clicking on that element fails.
I tried to set focus on needed element before clicking using the following code
Actions actions = new Actions(driver);
actions.MoveToElement(element);
actions.Perform();
But it fails. Can anyone please help?
One of two things. Is this on a popup by chance? If so you need to switch to the iframe.
public static void switchToIframe(string name)
{
_webDriver.SwitchTo().Frame(name);
}
If the element is off the page and it is a scrolling issue you can try this:
You can pass in a value of 100 to move down 100px.
public static void ScrollDownByAmount(string value)
{
var windowScroll = string.Format("window.scrollBy(0,{0})", value);
IJavaScriptExecutor javascript = (IJavaScriptExecutor)_webDriver;
javascript.ExecuteScript(windowScroll , "");
Thread.Sleep(500);
}
I have to develop a unit test which fails if element is present and passes the test if element is not present.
To be detailed, I have a simple form like name, email, address etc. When I click on the save button, error message is displayed if required fields are empty. If error message is displayed then I have to fail the test and if not displayed then pass the test. Is there any solution?
try
{
//Click on save button
IWebElement save_profile = driver.FindElement(By.XPath("//div[#class='form-group buttons']/div/input"));
save_profile.Click();
//Locate Error Message below the text box
IWebElement FirstNameError = driver.FindElement(By.XPath("//form[#class='default form-horizontal']/fieldset/div[4]/div[2]/span/div"));
//I want to fail the test here if above element is found
}
catch
{
//pass the test if element is not found in try statement
}
I think I am going in the wrong direction but couldn't find the solution. Please advice. Thansk in advance.
Following is the behavior of "findElement"
If the element you are looking exists, it returns the WebElement.
If the element does not exist, it throws Exception and if not handled properly leads troubles.
So use "findElements"(here observe 's' at the end)
Following is the behavior of "findElements"
It returns a list,
If the element exists, the size obviously more than 0,
If the element does not exist the size will be 0. So you can just put a if condition with size
Here is pseudo code in Java
if (driver.findElements(By.XPath("//div[#class='form-group buttons']/div/input")).size()>0)
//print element exists
else
//print element does not exists.
I hope the above helps.
You have two options to do this.
Firstly, by using Assert.assertTrue(boolean value);
try
{
//Click on save button
IWebElement save_profile = driver.FindElement(By.XPath("//div[#class='form-group buttons']/div/input"));
save_profile.Click();
//Locate Error Message below the text box
IWebElement FirstNameError = driver.FindElement(By.XPath("//form[#class='default form-horizontal']/fieldset/div[4]/div[2]/span/div"));
//I want to fail the test here if above element is found
Assert.assertTrue(false);
}
catch
{
//pass the test if element is not found in try statement
Assert.assertTrue(true);
}
Secondly, by using boolean return type if used inside a method.:
boolean isValidated = false;
try
{
//Click on save button
IWebElement save_profile = driver.FindElement(By.XPath("//div[#class='form-group buttons']/div/input"));
save_profile.Click();
//Locate Error Message below the text box
IWebElement FirstNameError = driver.FindElement(By.XPath("//form[#class='default form-horizontal']/fieldset/div[4]/div[2]/span/div"));
//I want to fail the test here if above element is found
isValidated =false;
return isValidated;
}
catch(Exception e)
{
//pass the test if element is not found in try statement
isValidated = true;
return isValidated;
}
If the method returns true, pass the test and vice versa
I need some help because I keep getting a StaleElementReference when I try to parse a list of a tags to click.
What I have done is on page land I iterate through the page and generate an object List<> with with all the a tags
private List<IWebElement> _pageLinks;
public List<IWebElement> pageLinks
{
get
{
if (_pageLinks == null)
{
_pageLinks = InfoDriver.FindElements(By.TagName("a")).ToList();
}
return _pageLinks;
}
}
Then I want to parse this list, and click each one and then go back to the page it was referenced from.
private static SeleniumInformation si = new SeleniumInformation(ffDriver);
si.pageLinks.ForEach(i =>
{
i.Click();
System.Threading.Thread.Sleep(1000);
ffDriver.Navigate().Back();
});
What happens is that after the first click it goes to the new page and then goes back to the starting page but it can't get the next link. I've tried setting it to a static element, setting a backing field so that it checks to see if there is data there already however it appears that on click the IwebElement looses the list and it doesn't rebuild the list either so I get a StaleElementReference exception not handled and element not found in cache.
Is this a bug in Selenium with the IWebElement class or am I doing something wrong? Any help would be greatly appreciated.
This is the expected behavior. You left the page the element was on. When you navigated back, it is a new page and that element is no longer on it.
To work around this I would suggest passing around Bys instead, if you can. Assuming your anchorlinks all have unique hrefs, you could instead generate a list as follows (java code, but should translate to c#):
private static List<By> getLinks(WebDriver driver)
{
List<By> anchorLinkBys = new ArrayList<By>();
List<WebElement> elements = driver.findElements(By.tagName("a"));
for(WebElement e : elements)
{
anchorLinkBys.add(By.cssSelector("a[href=\"" + e.getAttribute("href") + "\"]"));
//could also use another attribute such as id.
}
return anchorLinkBys;
}
I don't know the makeup of your page so I don't know if it is possible to generate By's dynamically that uniquely identify the elements you want. For example if all the elements have the same parent, you could use the css level 3 selector nth-child(n). Hopefully you get some ideas from the above code.
private void YourTest()
{
IWebDriver browserDriver = new FirefoxDriver();
browserDriver.Navigate().GoToUrl(pageUrl);
int linkCount= browserDriver.FindElements(By.TagName("a")).Count;
for (int i = 0; i <= linkCount-1; i++ )
{
List<IWebElement> linksToClick = browserDriver.FindElements(By.TagName("a")).ToList();
linksToClick[i].Click();
System.Threading.Thread.Sleep(4000);
if(some boolean check)
{
//Do something here for validation
}
browserDriver.Navigate().Back();
}
broswerDriver.Quit();
}