继续无法在货币SELENIUM JAVA上选择radioButton

时间:2015-07-28 04:12:13

标签: java selenium

我的代码看起来有点不对劲,因为有时候它可以选择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 个答案:

答案 0 :(得分:0)

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