[英]Unable to click a radio button which is in a different frame
我正在尝试单击其他框架(而不是父框架)中的单选按钮。 当我执行以下代码时,也不例外,但是令人惊讶的是,它甚至没有单击该按钮。 如果您对我的代码有任何想法/发现任何问题,请告诉我。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.