简体   繁体   中英

Java Selenium button click

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 :/

您可以对两个路径都使用此cssSelector:

WebElement nextButton = driver.findElement(By.cssSelector("#pagination-head span.hidden-xs.hidden-sm"));

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM