0

I am trying to navigate through all the available pages in a website, at the beginning after scrolling to the second page I was getting exception that there is no such element on the web page, then I realize, at some point the css selector is changed in the website. Sometimes it is like that WebElement nextButton = driver.findElement(By.cssSelector("#pagination-head>a>div>span.hidden-xs.hidden-sm")); and sometimes WebElement nextButton = driver.findElement(By.cssSelector("#pagination-head > a:nth-child(3) > div > span.hidden-xs.hidden-sm")); My question is how I can handle this in selenium, I checked whether there is a method to check somehow whether a given webelement exist or not but I could no find any :/

3 Answers 3

1

You could use this cssSelector for both paths:

WebElement nextButton = driver.findElement(By.cssSelector("#pagination-head span.hidden-xs.hidden-sm"));
Sign up to request clarification or add additional context in comments.

Comments

0

If its only these 2 options, you could work with a workaround if/else statement.

You could create a boolean checking if element can be found by your first findElement. If true, use your first code, else, use second code.

Comments

0

You can use if-else block if you are sure that the next button is identified only by those two locators. If in case on the third page the locator changes, your if-else block will not work. So, better approach is to go for xpath to identify the next button. You can use below sample code to locate your element

WebElement nextButton = driver.findElement(By.xpath(".//*[contains(text(),'(text on your next button)')]"));

nextButton.click();

Please replace "(text on your next button)" with the text displayed on your next button. The above code will perform the click operation on the element containing the text which you pass.

Hope this is helpful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.