在星期文本字段中输入值

enter the value in day of the week text field

我有一个场景,我需要在文本字段中发送值。这些值是 1 或 0,具体取决于星期几。在下面的场景中,我需要为当天输入“0”,为剩余天数输入“1”。我希望,从星期二开始,我会在星期二的文本字段中得到“0”,但它在所有文本字段中都显示为 0。下面是我的代码,从 sunday - tuesday 开始。

顺便说一句:id=w_1 是星期天,w-2 是星期一,w_3 是星期二。

谢谢!

public String enter0And1(String daysOfWeek) {

Calendar calendar = Calendar.getInstance();
int currentDay = calendar.get(Calendar.DAY_OF_WEEK);

WebElement sun = driver.findElement(By.id("w_1"));
    sun.sendKeys(Keys.CONTROL + "a");
    sun.sendKeys(Keys.DELETE);

    if(driver.findElement(By.id("w_1")).equals(currentDay)){
    sun.sendKeys(current_day_zero); 

    }
    else {
    sun.sendKeys(current_day_one);
    }



    WebElement mon = driver.findElement(By.id("w_2"));
    mon.sendKeys(Keys.CONTROL + "a");
    mon.sendKeys(Keys.DELETE);

    if(driver.findElement(By.id("w_2")).equals(currentDay)){
    mon.sendKeys(current_day_zero); 

    }
    else {
    mon.sendKeys(current_day_one);
    }


    WebElement tues = driver.findElement(By.id("w_3"));
    tues.sendKeys(Keys.CONTROL + "a");
    tues.sendKeys(Keys.DELETE);

    if(driver.findElement(By.id("w_3")).equals(currentDay)){
    tues.sendKeys(current_day_zero); 

    }
    else {
    tues.sendKeys(current_day_one);
    }

return daysOfWeek;



} 

HTML 星期二:

<tr>
<td><div width="60%" class="form_label" id="w_3_label">
Tuesday
</div>
</td>
<td><input type="text" id="w_3" onchange="calculateAvgDI()" value="" size="9" maxlength="9" name="dailyWeightGoal(tuesday)">
</td>

问题是您正在尝试将 WebElementcurrentDay 整数进行比较。相反,在 getAttribute().

的帮助下使用实际输入值

替换:

if(driver.findElement(By.id("w_1")).equals(currentDay)){
    sun.sendKeys(current_day_zero);
}
else {
    sun.sendKeys(current_day_one);
}

与:

int value = Integer.parseInt(driver.findElement(By.id("w_1").getAttribute('value'));
sun.sendKeys(value == currentDay ? current_day_zero : current_day_one);

你遇到的问题Alecxe已经指出了。作为替代方案,您可以尝试使用这段代码。

String day = new Date().toString().split(" ")[0]; //returns day of week as for eg. Wed
List<WebElement> days = driver.findElements(By
        .xpath("//input[contains(@name,'dailyWeightGoal')]")); // Will get list of all input elements
for (WebElement webElement : days) {
    if (webElement.getAttribute("name").contains(day.toLowerCase())) // since the attribute name contains day, 
                                                                    //so checking like wise according to scenario
        webElement.sendKeys("0");
    else
        webElement.sendKeys("1");
}