Selenium中WebElement Click()抛出NullPointerException问题求助
Let's walk through why you're hitting that NullPointerException and how to fix it step by step:
1. You Forgot to Initialize the Page Factory
The @FindBy annotation is part of Selenium's Page Factory pattern, which requires explicit initialization to bind your WebElement variables to actual elements on the page. Right now, your Asia variable is null because you never told Selenium to create that mapping.
Add this line right after you initialize the driver (either in setup() or at the start of your test method):
PageFactory.initElements(driver, this);
This scans your class for @FindBy annotations and populates the corresponding WebElements with live references to page elements.
2. Your Absolute XPath Is Extremely Fragile
Absolute XPaths (starting with /html/body/...) break easily if the page structure changes even slightly—like a new div being added or a component reordered. Instead, use a relative XPath that targets the element based on more stable attributes.
For example, if the 'Asia' button has a visible text label, you can target it with a more reliable relative locator:
@FindBy(xpath = "//div[contains(text(), 'Asia')]/ancestor::a") WebElement asiaButton;
You can also check the element's HTML via browser dev tools for unique classes or data attributes to use instead—relative locators are far less likely to break with minor page updates.
3. Improve Your Wait Strategy
While you're using implicit waits and Thread.sleep(), these aren't the most reliable ways to handle page loading. Explicit waits let you wait for a specific condition (like the element being clickable) instead of guessing a fixed time.
Replace your fixed delays with a WebDriverWait in your test method:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.elementToBeClickable(asiaButton)).click();
This will wait up to 10 seconds for the button to be ready to click, avoiding errors from elements not being fully loaded yet.
4. Verify Your Locator Works Manually
Before running your test, validate your XPath in the browser's dev tools:
- Right-click the 'Asia' button and select "Inspect"
- Open the console tab
- Type
$x("your-xpath-here")and hit enter—if it returns the correct element, your locator is good; if not, adjust it to target a more unique attribute.
Modified Full Code
Here's how your code should look after applying these fixes:
package com.stackroute.SeleniumProject; import java.time.Duration; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class Yatra { public static WebDriver driver = null; // Stable relative XPath targeting the Asia button @FindBy(xpath = "//div[contains(text(), 'Asia')]/ancestor::a") WebElement asiaButton; @BeforeClass public static void setup() { String chromePath = System.getProperty("user.dir") + "/lib/chromedriver.exe"; System.setProperty("webdriver.chrome.driver", chromePath); driver = new ChromeDriver(); } @AfterClass public static void close() throws InterruptedException { driver.quit(); // Use quit() to close all windows and end the driver session properly } @Test public void testAsiaButtonNavigation() throws InterruptedException { driver.manage().window().maximize(); driver.get("https://www.yatra.com/etw-desktop/"); // Initialize Page Factory to bind WebElements PageFactory.initElements(driver, this); // Wait for the button to be clickable before interacting WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.elementToBeClickable(asiaButton)).click(); // Wait for the new page to load and verify URL wait.until(ExpectedConditions.urlContains("city-list")); Assert.assertEquals("Failed to navigate to Asia city list", "https://www.yatra.com/etw-desktop/city-list", driver.getCurrentUrl()); } }
Additional Notes
- Use
driver.quit()instead ofdriver.close()in your@AfterClassmethod—it closes all browser windows and ends the driver session cleanly. - Avoid mixing implicit and explicit waits, as this can cause unexpected wait times. Stick to explicit waits for better control over element loading.
内容的提问来源于stack exchange,提问作者BSJ

