简体   繁体   English

WebDriver脚本,用于单击除特定名称不起作用的所有链接

[英]WebDriver script for clicking all links except one with particular name not working

I am in process of learning Selenium WebDriver 2 using Java/Junit with IntelliJ IDEA. 我正在使用带有IntelliJ IDEA的Java / Junit学习Selenium WebDriver 2。

The sample page I am using for creating scripts is http://newtours.demoaut.com/ 我用于创建脚本的示例页面是http://newtours.demoaut.com/

I am trying to create a script that will click on all the links on the page EXCEPT the "SUPPORT" link. 我正在尝试创建一个脚本,点击页面上的所有链接除了“SUPPORT”链接。

I've imported all the necessary libraries and 我已经导入了所有必要的库和

Here is the code that I tried to use but it gives an error: 这是我尝试使用的代码,但它给出了一个错误:

public class AllLinksExceptSupport{

WebDriver driver= new FirefoxDriver();
String url="http://newtours.demoaut.com/";

@Before
public void loadhomepage()
{
driver.get(url);

@Test
public void allexceptregister(){
   List<WebElement> alllinks = driver.findElements(By.tagName("a"));
for (int i =0; i<= alllinks.size()-1; i++){
    String oflinks = alllinks.get(i).getText();
    if(oflinks.equals("SUPPORT")){
      continue;
    }
     alllinks.get(i).click();
}
}
}

Here is the error message: 这是错误消息:

org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up. org.openqa.selenium.StaleElementReferenceException:在缓存中找不到元素 - 也许页面自查找以来已更改。

Can you please advise on what I'm doing wrong and what needs to be changed in the code/logic? 你能告诉我我做错了什么以及需要在代码/逻辑中改变什么?

Thank you. 谢谢。

The issue you're encountering is that when you click a link, you're leaving the page. 您遇到的问题是,当您单击链接时,您将离开该页面。 This makes the collection of elements in your List "stale". 这使得List中的元素集合“陈旧”。

This is an approach that should work for you. 这是一种适合您的方法。 Of course, this assumes that all of the links have different link text. 当然,这假设所有链接都有不同的链接文本。

List<WebElement> allLinks = driver.findElements(By.tagName("a"));
String ofLinks[] = new String[allLinks.size()];
for (int i = 0; i < allLinks.size(); i++){
    if(!allLinks.get(i).getText().equals("SUPPORT")){
       ofLinks[i] = allLinks.get(i).getText();
    }
}

for (int i = 0; i < allLinks.size(); i++){
    if (ofLinks[i] != null){
        driver.findElement(By.LinkText(ofLinks[i])).click();
    }
    driver.findElement(By.linkText("Home")).click();
}

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

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