like this '''no using like this '''
@FindBy(xpath = "/html/body/div/div/div[2]/div/div/div[3]/button[2]")
private WebElement submitSearchButton;'''''' find this element and make text variable '''no using like this '''
TPV'''
Assistant
Certainly! Instead of using an absolute XPath to locate the element, it's better to use relative locators like CSS selectors or relative XPath expressions. This makes your code more maintainable and less brittle to changes in the page layout.
Given the HTML element:
html
<span class="vehicle-title">TPV</span>
You can locate this element using its class attribute. Here's how you can do it:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class YourPageObject {
// Locate the element using CSS Selector
@FindBy(css = "span.vehicle-title")
private WebElement vehicleTitleElement;
// Alternatively, locate the element using Relative XPath
// @FindBy(xpath = "//span[@class='vehicle-title']")
// private WebElement vehicleTitleElement;
public String getVehicleTitle() {
return vehicleTitleElement.getText();
}
}
Explanation:
Why Not Use Absolute XPath?
Absolute XPaths (like /html/body/div/div/...) are fragile because any change in the DOM structure can break the locator. They are also harder to read and maintain.
Benefits of Using CSS Selectors or Relative XPaths:
Stability: They are less likely to break when the UI changes slightly.
Readability: Easier to understand and maintain.
Performance: CSS selectors are generally faster than XPath in most browsers.
Additional Tips:
Use Unique Attributes: If there's a unique identifier (like an ID), it's best to use it.
Avoid Overly Generic Classes: If the class vehicle-title is used multiple times, consider using more specific selectors or combining multiple attributes.