Selenium Webdriver代码适用于调试,但正常运行时noy

时间:2016-03-19 14:23:48

标签: java selenium selenium-webdriver

我正在尝试在列表框中选择一个项目。以下代码在调试应用程序时有效,但在正常运行时无效(如JUnit测试)

wait.until(ExpectedConditions.elementToBeClickable(
  By.xpath("//div[@id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span")
));
driver.findElement(
  By.xpath("//div[@id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span")
).click();

wait.until(ExpectedConditions.elementToBeClickable(
  By.xpath("//ul[@id='symptomHeadGroupDropDown_listbox']/li[5]")
));
driver.findElement(
  By.xpath("//ul[@id='symptomHeadGroupDropDown_listbox']/li[5]")
).click();

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

尝试此代码,它将等待每秒查找60秒,然后单击元素:

int flag=0,wait=0;
while(flag==0 && wait<60){
    try{
        driver.findElement(By.xpath("//div[@id='ContentArea']/div/div/div[2]/div/table/tbody/tr[2]/td/div/span/span/span[2]/span")).click(); 
        flag=1;
    }
    catch(Exception){
        driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
        wait++;
    }
 }

flag=0,wait=0;  

while(flag==0 && wait<60){
    try{
                driver.findElement(By.xpath("//ul[@id='symptomHeadGroupDropDown_listbox']/li[5]")).click(); 
        flag=1;
    }
    catch(Exception){
        driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
        wait++;
    }
} 

答案 1 :(得分:0)

我的理论是WebElement的状态在 wait.until 调用之间以及第二次解析它以调用click时发生变化。

不是多次解析 WebElement ,而是在调用 WebDriverWait的 WebElement 返回值上调用 click()

WebElement target1 = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span")));
target1.click();

WebElement target2 =wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[@id='symptomHeadGroupDropDown_listbox']/li[5]")));
target2.click();

或者,如果您不想将其存储为临时变量...

wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[@id='symptomHeadGroupDropDown_listbox']/li[5]"))).click();