我希望能够点击"或";Female"选项,通过参数
输入值。public void enter_gender_as(String gender) {
WebElement g = driver.findElement(By.cssSelector("input[value=(gender)]"));
g.click();
}
HTML片段方法:
public static void selectRadioButtonByValue(List<WebElement> radioButtons, String value) {
for (WebElement radioButton: radioButtons) {
if (radioButton.getAttribute("value").toLowerCase().equals(value.toLowerCase())) {
radioButton.click();
break;
}
}
}
用法:
List<WebElement> radioButtons = driver.findElements(By.id("gender"));
selectRadioButtonByValue(radioButtons, "male");
可选,参数为WebDriver driver
:
public static void selectRadioButtonByValue(WebDriver driver, List<WebElement> radioButtons, String value) {
for (WebElement radioButton: radioButtons) {
if (radioButton.getAttribute("value").toLowerCase().equals(value.toLowerCase())) {
radioButton.click();
break;
}
}
}
selectRadioButtonByValue(driver, radioButtons, "male");
你已经知道了,只要像这样写你的代码:
public void enter_gender_as(String gender) {
WebElement g = driver.findElement(By.cssSelector("input[value=(" + gender + ")]"));
g.click();
}
然后正确调用:
enter_gender_as("Male");
如果你想更花哨,那么你可以输入if
s来检查值是否不是Male
或Female
。你可以让gender
.toLowerCase()
。您还可以添加显式的等待,例如ExpectedCondition
来等待元素加载。但这是基本功能。这里有一个"花哨"的例子。例如:
public void enter_gender_as(String gender) {
if(!gender.equalsIgnoreCase("Male") && !gender.equalsIgnoreCase("Female")){
System.out.println("Not a valid value! Please enter Male or Female");
}
WebElement g = driver.findElement(By.cssSelector("input[value=(" + gender.toLowerCase + ")]"));
new WebDriverWait(driver, [int for timeout]).until(ExpectedConditions.visibilityOf(g));
g.click();
}