没有使用此HTML代码选择单选按钮.如何做到这一点


<input id="radio2" name="radioGroup" type="radio">
<label class="flRight" for="radio2">
::before
"Senior Citizen"
::after
</label>
WebElement senior = driver.findElement(By.id("radio2"));
senior.click();

现在的问题是代码无法单击所需的元素。

您需要诱导WebdriverWait。要点击单选按钮,请使用JavaScript Executor,因为webdriver点击和操作类都不工作

WebDriverWait wait = new WebDriverWait(driver, 20); 
WebElement item=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[@class='flRight' and @for='radio2']")));
JavascriptExecutor js= (JavascriptExecutor) driver; 
js.executeScript("arguments[0].click();", item);

试试这个:

WebElement senior = driver.findElement(By.xpath(".//div[@class='radioBtn']/label[2]"));
WebElement close = driver.findElement(By.xpath(".//div[@id='nvpush_cross']"));
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOf(close));
close.click();
senior.click();

代码以前不起作用,因为有弹出窗口,你需要关闭它。

使用WebDriverWait:

WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement senior = wait.until(ExpectedConditions.elementToBeClickable(By.id("radio2")));
senior.click();

看到网站后,看起来input不是你想要点击的元素,而是label。。。

所以只需将senior变量更改为:

WebElement senior = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='RadioButton']//label[@for='radio2']")));

在元素不可点击的情况下,将人为操作自动化的最佳方法是使用Actions:

WebElement senior = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='RadioButton']//label[@for='radio2']")));
Actions actions = new Actions(driver);
actions.moveToElement(senior).click().build().perform();  

(使用JavascriptExecutorexecuteScript并不能真正点击…它只是调用了一种可能很好但不适合测试的方法…(

作为最后手段,使用JavascriptExecutor:

JavascriptExecutor jse= (JavascriptExecutor) driver; 
jse.executeScript("arguments[0].click();", senior);

请尝试以下解决方案:

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[@class='flRight' and @for='radio2']")));
Actions action=new Actions(driver);
action.moveToElement(element).click().perform();

最新更新