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();

有什么想法吗?

试试这段代码,它将每秒等待 60 个 seeconds 找到并单击元素:

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++;
    }
} 

我的理论是,WebElement 的状态在等待调用和第二次解析它以调用 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();

最新更新