The correct way to locate a button by its exact visible text is using XPath with the text() function. Option D uses this correctly.
Option D uses a CSS selector with :contains, which is not supported in Selenium.
Options C and D look for id or name attributes with value 'Submit', which may not exist.
public class LoginPage { @FindBy(id = "username") private WebElement usernameInput; public void enterUsername(String username) { usernameInput.sendKeys(username); } }
The @FindBy annotation creates a proxy for the element. The actual search happens when the element is used.
If the element is not found, Selenium throws NoSuchElementException at the time of interaction (sendKeys).
NullPointerException does not occur because the proxy is not null.
TimeoutException is not immediate unless explicit waits are used.
public class FormPage { @FindBy(css = "button.submit") private WebElement submitButton; public FormPage(WebDriver driver) { PageFactory.initElements(driver, this); } public WebElement getSubmitButton() { return submitButton; } } // In test method: FormPage page = new FormPage(driver); WebElement btn = page.getSubmitButton(); System.out.println(btn == null);
PageFactory.initElements creates a proxy for the WebElement fields.
The variable 'submitButton' is not null after initialization, so 'btn == null' prints false.
No exception is thrown at initialization because the element is not searched yet.
public class DashboardPage { @FindBy(xpath = "//div[@class='menu'][1]") private WebElement firstMenu; @FindBy(css = "div.menu:nth-child(1)") private WebElement firstMenuCss; }
The XPath expression selects the first div with class 'menu' correctly.
The CSS selector 'div.menu:nth-child(1)' selects div.menu elements that are the first child of their parent, which may not be the first div.menu overall.
This causes the CSS selector to not find the intended element, leading to runtime errors when used.
Option B is incorrect because @FindBy supports direct use of xpath or css parameters.
Using @FindBy with PageFactory creates proxies for elements, but does not wait for elements to be ready.
Adding explicit waits before interacting ensures elements are present and ready, handling dynamic changes well.
Implicit waits alone are less reliable for dynamic content.
Locating elements inside test methods each time (option C) reduces code reuse and clarity.
Refreshing the page (option C) is inefficient and not practical.