使用selenium webdriver在同一页面上逐个单击链接

时间:2014-01-30 12:53:00

标签: java selenium

我正在尝试点击状态链接给定网址然后打印下一页的标题然后返回,然后使用for循环动态单击另一个状态链接。但循环在初始值后停止。
我的代码如下:

 public class Allstatetitleclick {  
    public static void main(String[] args) {        
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("http://www.adspapa.com/");      

        WebElement catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table"));
        List<WebElement> catValues = catBox.findElements(By.tagName("a"));

        System.out.println(catValues.size());

        for(int i=0;i<catValues.size();i++){

            //System.out.println(catValues.get(i).getText());       
            catValues.get(i).click();
            System.out.println(driver.getTitle());
            driver.navigate().back();

        }
        System.out.println("TEST");
    }
}

2 个答案:

答案 0 :(得分:3)

问题是在导航回来之前找到的元素将会过期。因此,我们需要在导航回来之后更新代码以重新构造元素。

更新以下代码:

        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("http://www.adspapa.com/");      

        WebElement catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table"));
        List<WebElement> catValues = catBox.findElements(By.tagName("a"));

        for(int i=0;i<catValues.size();i++)
        { 
            catValues.get(i).click();
            System.out.println(driver.getTitle());
            driver.navigate().back();
            catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table"));
            catValues = catBox.findElements(By.tagName("a"));
        }
        driver.quit();

我已经测试了上面的代码并且工作正常。您可以根据自己的使用情况改进上述代码。

答案 1 :(得分:-2)

注意:我已经执行了这个并且它现在工作正常。它会给你大小并点击每个链接。这是你需要进入框架的问题。 它有一个框架,您需要切换。 请复制并粘贴并执行它。 希望你找到答案。