有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

继续未能选择JAVA上的radioButton

我的代码似乎有点不对劲,因为有时它可以在单选按钮上选择货币,有时它不工作。有没有建议通过添加计时器或其他方法来改进代码?谢谢

HTML:

id: enumTable_data

代码:

private WebElement getRowForCurrency (String currency)  {
        AbstractPage page = new AbstractPage();
        String[] frame = {"i2ui_shell_content","rcp_content"}; 
        page.switchToFrame(frame);  
        By cell = page.waitUntilPresent(By.xpath("//table[@id='enumTable_data']//nobr[text()[contains(.,'" + currency + "')]]"));
        WebElement currentElement = page.browser().findElement(cell);
        while(!currentElement.getAttribute("tagName").equals("TR")) {
            currentElement = currentElement.findElement(By.xpath(".."));
        }
        return currentElement;
    }

    public void selectCurrency (String currency)    {
        // find the text and get the parent, that is the row that contains the radiolist
        JLog.write("Select Currency: " + currency);
        WebElement row = getRowForCurrency(currency);
        if (row != null)    {
            WebElement radioButton = row.findElement(By.cssSelector("input[type='radio']"));
            if (null == radioButton)    {
                JLog.error("Found Document Row, but unable to find document radio button: " + currency, TakeScreenshot.True);
                return;
            }
            radioButton.click();
        } else  {
            JLog.error("Unable to find currency: " + currency, TakeScreenshot.True);
        }
    }

共 (1) 个答案

  1. # 1 楼答案

    1. you need to wait for the element to be present in the screen 
    
     public static WebElement findElement(WebDriver driver, By selector, long timeOutInSeconds) {
        WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
        wait.until(ExpectedConditions.presenceOfElementLocated(selector));
    
        return findElement(driver, selector);
      }
    
      public static WebElement findElement(WebDriver driver, By selector, long timeOutInSeconds, String timeOutMessage) {
        try {
          WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
          wait.until(ExpectedConditions.presenceOfElementLocated(selector));
    
          return findElement(driver, selector);
        } catch (TimeoutException e) {
          throw new IllegalStateException(timeOutMessage);
        }
      }
    
      public static WebElement findElementSafe(WebDriver driver, By selector, long timeOutInSeconds) {
        try {
          return findElement(driver, selector, timeOutInSeconds);
        } catch (TimeoutException e) {
          return null;
        }
      }
    
      public static WebElement findElementSafe(SearchContext context, By selector) {
        try {
          return context.findElement(selector);
        } catch (Exception e) {
          return null;
        }
      }