关于硒webdriver的错误

时间:2016-09-17 06:10:30

标签: selenium xpath

这是我的selenium webdriver代码,当我运行脚本时出现错误

线程中的异常" main" org.openqa.selenium.NoSuchElementException:无法找到元素:{"方法":" xpath","选择器":" .//* [ @id ='内容'] /表/ tbody的/ TR [0] /第"} 命令持续时间或超时:48毫秒

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class DropdownCommands{
    public static void main(String[] args){
        WebDriver driver = new FirefoxDriver();

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

        driver.get("http://toolsqa.wpengine.com/automation-practice-table");
        String sRow = "1";
        String sCol = "2";

        //Here we are locating the xpath by passing variable  in the xpath
        String sCellValue = driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr[" + sRow + "]/td[" + sCol + "]")).getText();
        System.out.println(sCellValue);
        String sRowvalue = "Clock Tower Hotel";

        //First Loop will find the 'Clock tower Hotel' in the first column
        for(int i=0; i<=5; i++){
            String sValue = null;
            sValue =  driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr[" + i + "]/th")).getText();
            if(sValue.equals(sRowvalue)){
                for(int j=1; j<=5; j++){
                    String sColumnValue = driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr[" + i + "]/td["+ j +"]")).getText();
                    System.out.println(sColumnValue);
                }
                break;
            }
        }
        driver.close();
    }
}

1 个答案:

答案 0 :(得分:0)

你正在给予&#34;我&#34; &#34; for&#34;循环为0,但没有tr [0],tr以tr [1]开头。因此,你得到了#34;无法定位元素&#34;错误。

修改代码如下。它会起作用。

for(int i = 1; i&lt; 5; i ++){             String sValue = null;             sValue = driver.findElement(By.xpath(&#34; .// [@ id =&#39; content&#39;] / table / tbody / tr [&#34; + i +&#34 ] /第&#34;。))的getText();             如果(sValue.equals(sRowvalue)){                 for(int j = 1; j&lt; = 5; j ++){                     String sColumnValue = driver.findElement(By.xpath(&#34; .// [@ id =&#39; content&#39;] / table / tbody / tr [&#34; + i +& #34;] / TD [&#34 + J +&#34;]&#34;。))的getText();                     的System.out.println(sColumnValue);                 }                 打破;             }         }

输出:

沙特阿拉伯 麦加 601米 2012 2