javaselenium-webdriverxpathdomxpath

Looking for précised/Efficient Dynamic Xpath


I am practicing the Xpath creation on (any fight booking search engine - MMT as reference) after long time and have few queries related to dynamic xpath. My Query is below

  1. Have written a xpath to find the airlinename from list of LineItem. Below is Xpath which is returning 3rd line item details. Is this efficient or précised to fetch the the 3rd line item?

//div[@class="clusterContent"]/div/div[3]/div/div[2]/div/div//following::div/p[2]

  1. To fetch all the line item I have written the xpath as below

//div[@class='clusterContent']/div will give me list of line items, will store this in List and i will iterate the below xpath till this size.

@FindBy(xpath="//div[@class='clusterContent']")
List<WebElement> totalNoFlight;

    public void getFlightCount()
        {
            int size = totalNoFlight.size();
            for(int i=0;i<size;i++)
            {
                    WebElement videoCliplnk = driver
                            .findElement(By.xpath("//div[@class='clusterContent']/div/div["+i+"]/div/div[2]/div/div//following::div/p[2]"));
                     String videoLinkhrs = videoCliplnk.getText();
            }   
        }

Is this a correct way to write these king of Dynamic xpaths in POM page factory design pattern?

enter image description here


Solution

  • To get the Airline name from search results, Use following xpath.

    //div[@class='makeFlex spaceBetween']//p[contains(@class, 'airlineName')]
    

    Ideally you should use some delay to load the page first, Then use below code.

    List<WebElement> totalNoFlight = driver.findElements(By.xpath("//div[@class='makeFlex spaceBetween']//p[contains(@class, 'airlineName')]"));
    
    for(int i = 0; i < totalNoFlight.size(); ++i) {
         system.out.println(totalNoFlight.get(i).getText());
    }