如何解决线程main中的异常

时间:2015-07-02 12:05:32

标签: java selenium selenium-webdriver

在我的下面的代码中,出现了以下错误:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"CarId"}
Command duration or timeout: 60.16 seconds

它适用于For循环的第一次迭代。对于"第二次迭代"我收到了上述错误

我尝试使用try catch语句和wait语句。

非常感谢任何帮助。

    public class Myclass {

    static WebDriver driver = new FirefoxDriver();

    public static void main(String[] args) throws IOException, 
    JXLException,BiffException,FileNotFoundException, 
    InterruptedException, Exception {

    // driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

    driver.get("url");

     //todostuff 

    FileInputStream fi = new FileInputStream("D:\\Result\\Myclass.xls");

    Workbook w = Workbook.getWorkbook(fi);

    Sheet s;

    s = w.getSheet("Sheet1");

    for(int row=1; row <=s.getRows();row++)

    {

    String ItemCode = s.getCell(0, row).getContents();

    System.out.println("Car "+CarA);

    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

    driver.findElement(By.id("CarId")).clear();

     //todo stuff

    String SOH = new Myclass().getIframe("DSajdadaj");

    int y=0;

    FileOutputStream fo = new FileOutputStream("D:\\Output.xls");

    WritableWorkbook wb = Workbook.createWorkbook(fo);

    WritableSheet ws = wb.createSheet("Sheet1", 0);

    Label Sheet1 = new Label(0,y,SOH);

    ws.addCell(Sheet1);

    Thread.sleep(3000);

    System.out.println(SOH);

    Thread.sleep(1000);

    wb.write();

    wb.close();

    y++;

        }

    fi.close();

    driver.quit();

    }

    public String getIframe(String id) {

    //todo stuff

    }}

    return SOH;

    }

1 个答案:

答案 0 :(得分:1)

从您的代码中,您似乎正在切换到getIframe中的框架。但是,一旦你的操作完成,忘记切换到默认[driver.switchTo().defaultContent();]

  public String getIframe(String id) {
    String Value = "";
    final List<WebElement> iframes = driver.findElements(By.tagName("iframe"));
    for (WebElement iframe : iframes) {
         if (iframe.getAttribute("id").equals(id)) {
            driver.switchTo().frame(id);//switch happens
            Value = driver.findElement(By.xpathdfdgdg")).getText();
            System.out.println("erer" + Value);
        }
    }
    return Value;
}


   for (int row = 1; row <= s.getRows(); row++) {

        String ItemCode = s.getCell(0, row).getContents();

        System.out.println("Car " + CarA);

       // driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);  No need to put implicit wait in for loop.It can be outside as well
        driver.switchTo().defaultContent();//Have to switch to the default because the element is in the top window not inside frame
        driver.findElement(By.id("CarId")).clear();