如何清除文本框中的文本?

时间:2018-12-24 11:31:16

标签: java selenium-webdriver xpath css-selectors webdriverwait

webdriver clear()不会清除现有文本

我尝试过clear(),但是它不起作用,所以尝试了.sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.BACK_SPACE)),但是我的前辈不希望我使用这些键。所以不确定如何清除文本?

元素的HTML:

<input name="Quantity_110787" type="number" min="0" ng-model="invoiceLine.quantity" class="form-control ng-pristine ng-valid ng-not-empty ng-valid-min ng-touched" ng-keypress="$ctrl.preventKey($event)" aria-invalid="false">

代码试用:

public void sendText(String text) {
        for (String control : controls) { 
        if(getWebDriver().findElement(By.cssSelector(control)).getAttribute("type").contains("number")) {
                getWebDriver().findElement(By.cssSelector(control)).sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.BACK_SPACE), text);
                break;
            }
        }

我希望清除文本字段,因此我可以输入新文本。请帮忙。

3 个答案:

答案 0 :(得分:2)

这应该像@Dark Knight所说的那样工作,

driver.findElement("locator").clear();

尝试点击

 driver.findElement("locator").click();
 driver.findElement("locator").clear();

否则尝试使用sendKeys

driver.findElement("locator").click();
driver.findElement("locator").sendKeys("");

否则尝试JS:

WebElement wb = driver.findElement("locator");
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].value='';", wb);

谢谢

答案 1 :(得分:0)

尝试这种方式。

driver.findElement("locator").clear();

答案 2 :(得分:0)

所需元素是Angular元素,因此要调用clear()方法,您需要诱使 WebDriverwait 使元素可点击,并且可以使用以下任一解决方案:

  • cssSelector

    WebElement elem = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.form-control.ng-pristine.ng-valid.ng-not-empty.ng-valid-min.ng-touched[type='number'][name^='Quantity_']")));
    elem.click();
    elem.clear();
    
  • xpath

    WebElement elem = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='form-control ng-pristine ng-valid ng-not-empty ng-valid-min ng-touched' and @type='number'][starts-with(@name, 'Quantity_')]")));
    elem.click();
    elem.clear();