dark_space
dark_space

Reputation: 179

find text in id then find class in the same id

The code below asks for a user input (year) and i want to use the same input to first check if the text (for eg. 2014) input by a user in the div class is in that particular PagePostsSectionPaglet and if yes, find div class="_5sem"in the same div id to perform action on its other webelements?

        Scanner reader = new Scanner(System.in);  // Reading from System.in
        System.out.println("Enter a year: ");
        String year = reader.next(); // Scans the next token of the input 

        WebElement yearButton = driver.findElement(By.xpath("//a[contains(@data-key,'" + year + "')]"));                        
        yearButton.click(); 

enter image description here

Upvotes: 0

Views: 75

Answers (2)

Mesut GUNES
Mesut GUNES

Reputation: 7401

You can create a xpath which look for ids starts-with your constant part of ids like "//*[starts-with(@id, 'PagePostsSectionPagelet')]". Then you can find all the divs and sort in list webelement by this xpath. Finally you can iterate over the list and if one has the text "2014" then you can click or whatever you want with it. See the code below:

List <WebElement> PagePostsSectionPagelet = driver.findElements(By.xpath("//*[starts-with(@id, 'PagePostsSectionPagelet')]"));

for (WebElement elm : PagePostsSectionPagelet){
        System.out.println(elm.findElement(By.cssSelector(".clearfix > span")).text)    
    }
}

Upvotes: 1

Learner
Learner

Reputation: 5292

You may try something XPATH like- If it exists the it will return webelement otherwise None.

//div[@id='PagePostsSectionPagelet']//span[text()='2014']/preceding::div[2]/following-sibling::div[1]//div[@class='_5sem']

Selenium expression like-

driver.findElements(By.xpath("//div[@id='PagePostsSectionPagelet']//span[text()='2014']/preceding::div[2]/following-sibling::div[1]//div[@class='_5sem']"))

Upvotes: 0

Related Questions