What is the reason for Selenium's @FindBy method not functioning properly with name, xpath, and css selectors?

Having trouble using @FindBy() in my Java program with Selenium. The program consists of multiple lines and I'm looking to share tasks between classes, starting with identity verification. I've created a class that includes login credentials for username and password.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class LoginPageNew {

    WebDriver webDriver;

    public LoginPageNew(WebDriver driver) {
        this.webDriver = driver;
    }

    @FindBy(css = "[name='username']")
    @CacheLookup
    WebElement username;

    @FindBy(how = How.NAME, using = "password")
    @CacheLookup
    WebElement password;

    @FindBy(how = How.XPATH, using = "//button[normalize-space()='Login']")
    @CacheLookup
    WebElement submit_btn;

    public void loginPage() {
        username.sendKeys("Admin");
        password.sendKeys("admin123");
        submit_btn.click();
    }
}

Additionally, I created another class:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserFactory {

    static WebDriver driver;

    public static WebDriver startBrowser(String browserName, String url) {
        if (browserName.equals("chrome")) {
            driver = new ChromeDriver();
        }
        driver.manage().window().maximize();
        driver.get(url);
        return driver;
    }
}

And finally, a test class:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;

public class VerifyLoginPage {

    @Test
    public void checkValidUser() {
        WebDriver webDriver = BrowserFactory.startBrowser("chrome", "http://opensource-demo.orangehrmlive.com/");
        LoginPageNew pageNew = PageFactory.initElements(webDriver, LoginPageNew.class);
            pageNew.loginPage();
    }
}

I intend to work on the site "https://opensource-demo.orangehrmlive.com/" using the credentials "Admin" and "admin123" with this setup for testing purposes.

In my attempts to resolve the issue, I used various types of @FindBy, but encountered the same error consistently.

@FindBy(name="username"), @FindBy(css = "[name='username']"), 
@Find By(xpath = "//input[@placeholder='Username']")
@Find By(xpath = "(//input[@placeholder='Username'])[1]")
@Find By(how = How. NAME, using = "username")...

The error message received is:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"[name='username']"}
 (Session info: chrome=109.0.5414.76)
 For documentation on this error, please visit: https://selenium.dev/exceptions/#no_such_element
 Build info: version: '4.7.2', revision: '4d4020c3b7'
 System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '11.0.16'
 Driver info: org.openqa.selenium.chrome.ChromeDriver
 Command: [f3cd14b65540143dd77567fdbdd70945, findElement {using=css selector, value= 
 [name='username']}]
 Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 109.0.5414.76, 
 chrome: {chromedriverVersion: 109.0.5414.74 (e7c5703604da..., userDataDir: 
 C:\Users\hp\AppData\Local\T...}, goog:chromeOptions: {debuggerAddress: localhost:64620}, 
 networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: WINDOWS, proxy: 
 Proxy(), se:cdp: ws://localhost:64620/devtoo..., se:cdpVersion: 109.0.5414.76, setWindowRect: 
 true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 
 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, 
 webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}

Answer №1

I'm going to include this snippet of code

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

Appreciate it BMW83

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to convert a Java object into a JSON string while ensuring that all special characters are

Is there a method to transform a Java object into a string with the following criteria? It is important that all field names are properly escaped, and the records are separated by "\n". { "content":"{\"field1\":123, \"field2\":1, ...

There was a limitation in Python that prevented the transmission of Backspace keys

Currently, I am facing an issue while attempting to download a file from the Thai government website. Despite my efforts to backtrack to the previous page, remove the old code (hscode), which I had already downloaded, and replace it with a new one, I encou ...

AngularJS, Apache Tomcat, and hashtag URLs

I feel like I'm stuck in a nightmare trying to figure out how to work with Tomcat Apache. My Goal One issue I've encountered in AngularJs is the # problem like www.example.com/#/aboutus After doing some research, I discovered that $locatio ...

Contrasting the uses of element(...) versus element(...).getWebElement() in Protractor

What is the advantage of using element(...).getWebElement() instead of element(...) when they both perform similarly? Why are there two different APIs for the same purpose? ...

Troubleshooting problem with Firefox and Selenium: Firefox remains unresponsive despite being updated

I encountered an issue while running a functional test that involves opening a Firefox browser with Selenium. Despite trying to troubleshoot by updating Selenium and re-installing Firefox, the error message persists. Here's the detailed error message ...

Protractor unexpectedly giving back a promise instead of the expected attribute value

I'm facing a challenge where I am attempting to extract the value of an HTML attribute and store it in a variable named url_extension. However, instead of getting the desired value, I keep receiving a Promise object. Below is my code snippet: (Please ...

Collaborate and apply coding principles across both Android and web platforms

Currently, I am developing a web version for my Android app. Within the app, there are numerous utility files such as a class that formats strings in a specific manner. I am wondering if there is a way to write this functionality once and use it on both ...

How to access a Selenium element using JavaScriptExecutor

My task involves working with a collection of elements in Selenium, specifically located using the By.CssSelector method: var contentRows = new List<TableRow>(); for (var i = 1; i < PositiveInfinity; i++) { var cssSelectorToFind = $"tbody &g ...

Use Node.js with Selenium and WebdriverIO to simulate the ENTER keypress action on

I have put in a lot of effort trying to find the solution before resorting to asking this question, but unfortunately I have not been successful. All I need to know is how to send special characters (such as the enter key and backspace) with Node.js using ...

Guide to saving detailed log information from Edge Driver (Chromium) to a text file in Java

After reading through this informative article, I successfully launched an Edge Chromium browser. else if (browser.equalsIgnoreCase("edge")) { System.setProperty("webdriver.edge.driver", System.getProperty("user.dir") + "\\src\\tes ...

Strategies for managing a situation where one popup is activated by another popup

Trying out the latest version of Selenium (2.29) with Firefox 8.0.1 after encountering a modal dialog issue that limited me to using FF 11 as the maximum version. I have an icon that, when clicked, triggers some javascript code. Using the following snippet ...

I'm currently struggling with some code that's not giving me the desired output. Is there a way you could suggest to help me scrape text from Facebook comments on a live stream or post?

I am interested in scraping Facebook comments from FB Live or posts. Does anyone know of a way to do this? If so, please provide assistance. I have attempted the following code without success: comments = driver.find_elements_by_css_selector('.UFICo ...

How can I transform a list of company names into corresponding LinkedIn links using a scraper tool?

Using Python, Selenium, and BeautifulSoup, I created a custom LinkedIn scraper that extracts relevant information about companies from their LinkedIn profiles such as details on competitors. However, my current challenge lies in managing a list of company ...

Having trouble running selenium webdriver in robot framework

Encountering an issue while attempting to set up Selenium Webdriver with Robot Framework. WebDriverException: Message: Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability pro ...

Managing duplicate xpaths in Selenium with Java

Seeking assistance with dynamically selecting items from a drop-down menu based on input. The challenge arises when values share the same name. For example, consider this Cucumber statement: When I go to the "Inventory" / "Inventory" application When ut ...

What is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

Create a single HTMLTestRunner file while executing multiple test classes

I've been struggling to configure HTMLTestRunner to consolidate output into a single file when running multiple test classes. Despite extensive research, I have not been successful in achieving this. Here is an example of my setup: class TestOne(uni ...

Today, I am experimenting with HTML5 File Upload using Capybara and Selenium Webdriver in Ruby

I have encountered a problem with a simple modal that allows users to upload a file using a browse button. Due to some unknown issue, possibly related to the fact that it is an HTML5 file input and the browser adds its own functions to it, testing this has ...

Step-by-step guide on choosing a dropdown menu within a submenu using Selenium WebDriver

I am a beginner with Selenium and I'm attempting to choose an option (Job Title) from the sub menu (Job) under the main menu 'Admin' on OrangeHRM website. When running my script, it correctly clicks on Admin but instead of hovering over "Jo ...

Unable to locate the Selenium element despite its confirmed presence

Having some difficulty locating an element at this link. I am looking to extract the names of the matches with the following code: WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[7]/div[1]/div/div/div[4]/div/d ...