主页面包含300多个链接,点击主页面上的每个链接打开新窗口(当然)与表格。我总是需要来自同一位置的表值,但是...有时(但有时只是)(必要的)表值也是一个链接,在点击它之后打开新窗口。
如果单击该表值打开新窗口(使用新表)我需要来自该新窗口的特定表值,否则(如果原始表值不是链接)我只需要原始表值。
我尝试使用下面的代码,但发生错误......
线程中的异常" main" org.openqa.selenium.NoSuchElementException:无法找到元素:{"方法":" xpath","选择器":" .//* [ @id =' aodds-信息'] / DIV [2] /表/ tbody的/ TR [3] / TD [2]"} 命令持续时间或超时:33毫秒
package newpackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class newdist {
public static void main(String[] args) throws IOException, InterruptedException {
// Open main page
WebDriver driver = new FirefoxDriver();
driver.get("Main page link");
Thread.sleep(5000);
// Maximize main page window
driver.manage().window().maximize();
Thread.sleep(1000);
// List off all links on Main page
List<WebElement> lista1 = driver.findElements(By.cssSelector(".first-cell.tl>a"));
// loop trough all links on Main page
for(int j=0;j<lista1.size();j++){
WebElement link = lista1.get(j);
List<WebElement> links = driver.findElements(By.cssSelector(".first-cell.tl>a"));
String homePage = driver.getWindowHandle();
link.click();
Thread.sleep(3000);
// Window handles block
Set<String>windows=driver.getWindowHandles();
Iterator iterator = windows.iterator();
String currentWindowId;
while (iterator.hasNext()){
currentWindowId = iterator.next().toString();
if(! currentWindowId.equals(homePage)){
driver.switchTo().window(currentWindowId);
Thread.sleep(3000);
// "clicking" on specific table value (clicking maybe opens new window)
driver.findElement(By.xpath(".//*[@id='sortable-1']/tbody/tr[6]/td[1]/span")).click();
Thread.sleep(3000);
// if clicking opens new window print specific value from table in that new window
try {
String s0 = driver.findElement(By.xpath(".//*[@id='aodds-info']/div[2]/table/tbody/tr[3]/td[2]")).getText();
System.out.println(s0);
}
// if clicking doesn't open new window print current table value from current window
catch (NoSuchElementException e){
String s0 = driver.findElement(By.xpath(".//*[@id='sortable-1']/tbody/tr[6]/td[1]/span")).getText();
System.out.println(s0);
}
// return to Main page
finally{
driver.close();
driver.switchTo().window(homePage);
Thread.sleep(2000);
}
}
}
}
}
}
答案 0 :(得分:0)
从NoSuchElementException
导入java.util
。要捕获Web元素异常,您需要从org.openqa.selenium
导入。
作为旁注,使用explicit and implicit wait比使用Thread.sleep
要好得多。