无法单击位于不同框架中的单选按钮

Unable to click a radio button which is in a different frame

我正在尝试单击位于不同框架(不在父框架中)的单选按钮。当我执行下面的代码时没有异常,但令人惊讶的是它甚至没有点击按钮。如果您在我的代码中有任何 thoughts/find 问题,请告诉我。

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Practise_Radio_Checkbox {

    public static void main(String[] args) throws InterruptedException {

         System.setProperty("webdriver.chrome.driver", "D:\Learning\API\Selenium\chromedriver.exe");


            WebDriver browser = new ChromeDriver();

            browser.manage().timeouts().implicitlyWait(10L, TimeUnit.SECONDS);

            browser.manage().window().maximize();


            browser.get("http://www.quackit.com/html/codes/html_radio_button.cfm");

            WebElement e1 = browser.findElement(By.name("result2"));


            browser.switchTo().frame(e1);

            browser.findElement(By.xpath("html/body/form/input[1]")).click();

            browser.quit();


    }

}

我可以单击单选按钮,它位于与父项不同的框架中。我认为问题是,你试图切换框架“按名称 - findElement(By.name("result2"))"。我用 Xpath 试过了。它对我有用,我可以点击收音机按钮“红色”。

这是工作代码:-

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class iframeradiobutton {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("http://www.quackit.com/html/codes/html_radio_button.cfm");

        //Switch to Iframe
        WebElement iframe = driver.findElement(By.xpath("/html/body/div[1]/div/article/div[2]/div[2]/div[2]/iframe"));
        driver.switchTo().frame(iframe);
        driver.findElement(By.xpath("/html/body/form/input[1]")).click();
        System.out.println("Clicked on Radio Button Red");
        driver.switchTo().defaultContent();// Iframe is Switched to Main Again

        driver.close(); // Closes the current driver instance. 
    }
}

输出供您参考

首先,它适用于 Firefox(即使没有任何明确的等待):

WebDriver browser = new FirefoxDriver();

在 Chrome,出于某种未知原因,您必须 通过 javascript:

进行点击
WebElement red = driver.findElement(By.xpath(".//input[@type='radio' and @value='Red']"));
JavascriptExecutor executor = (JavascriptExecutor)browser;
executor.executeScript("arguments[0].click();", red); 

此外,我必须添加一个显式等待以等待框架出现:

WebDriverWait wait = new WebDriverWait(webDriver, 10);
WebElement iframe = wait.until(ExpectedConditions.presenceOfElementLocated(By.name("result2")));
driver.switchTo().frame(iframe);