简体   繁体   English

Java Selenium按钮单击

[英]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. 我试图浏览网站上所有可用的页面,在滚动到第二页后的开始,我发现网页上没有这样的元素,然后我意识到,在某些时候css选择器已更改在网站上。 Sometimes it is like that WebElement nextButton = driver.findElement(By.cssSelector("#pagination-head>a>div>span.hidden-xs.hidden-sm")); 有时就像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")); 有时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 :/ 我的问题是如何在硒中处理此问题,我检查了是否有一种方法可以某种方式检查给定的webelement是否存在,但我找不到任何:/

您可以对两个路径都使用此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. 如果只有这两个选项,则可以使用解决方案if / else语句。

You could create a boolean checking if element can be found by your first findElement. 您可以创建布尔检查是否可以通过第一个findElement找到元素。 If true, use your first code, else, use second code. 如果为true,则使用您的第一个代码,否则,请使用第二个代码。

You can use if-else block if you are sure that the next button is identified only by those two locators. 如果确定下一个按钮仅由这两个定位器标识,则可以使用if-else块。 If in case on the third page the locator changes, your if-else block will not work. 如果在第三页上定位符发生更改,则if-else块将不起作用。 So, better approach is to go for xpath to identify the next button. 因此,更好的方法是使用xpath来标识下一个按钮。 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. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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