user2917239
user2917239

Reputation: 898

Setting focus with Selenium WebDriver

I have a Selenium WebDriver test where I enter some text into a text input box

var input_Note = Driver.Instance.FindElement(By.Id("note"));
        input_Note.SendKeys("test");

I then attempt to click on the Save button, but it does not work. I was previously using Coded UI where there is a SetFocus element that points the focus towards whichever element you are targeting. Is there something similar in Selenium?

var button_Save = Driver.Instance.FindElement(By.Id("save"));
button_Save.Submit();

Upvotes: 0

Views: 1432

Answers (1)

mutt
mutt

Reputation: 793

Sometimes depending on how the page is loaded it will exist and then not exist and then exist again. I have found that waiting on the element is a good idea and sometimes will put two waits back to back for the specific element that this will solve this issue(I would say a programming fix for a double wait would be desired...screen flashing too much at that point). This really depends on the load pattern of your application though.

    WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
    wait.Until (d=> Driver.Instance.FindElement(By.Id("save")));

I would also utilize the .click if it is a button. In general it should be a submit action, but it doesn't always have to be a submit action. There may also be situations where you might need to gain the focus...which shouldn't be programmed that way, but in case it is you can utilize the Actions class and move the mouse to the element and then perform a click action on the element.

    //C# example:
    OpenQA.Selenium.UI.Interactions.Actions actions = new OpenQA.Selenium.UI.Interactions.Actions();
    actions.MoveToElement([Instance of Web Element goes here]).Perform();
    actions.Click([Instance of Web Element goes here]).Perform();

In general you could just use the actions.Click, but figured I would give both.

One of the above should work just fine. If it does not work please provide a specific error message you get with Selenium and the specific html structure of the page being utilized.

Upvotes: -1

Related Questions