2016-08-15 55 views
2

我想清除&更改給定url上輸入的值。我使用的js什麼都不做,並且不會導致錯誤。爲什麼會發生這種情況,我該如何解決?爲什麼我無法使用javascript清除輸入字段?

@Test 
public void clearField() throws Exception { 
    String url = "https://sfbay.craigslist.org/search/pen/apa?hasPic=1&search_distance=25&" + 
      "postal=94014&nh=75&nh=80&min_price=1500&max_price=2500&bedrooms=1&bathrooms=1"; 
    //url = "https://sfbay.craigslist.org/search/pen/apa?housing_type=1";//Clear & set value works with this url. 
    browser.get(url); 

    WebElement element = browser.findElement(By.name("search_distance")); 
    String char_sequence = "10"; 

    //Clear the field 
    send_keys_v2(element, ""); 
    //Re write the field 
    send_keys_v2(element, char_sequence); 
} 

public void send_keys_v1(WebElement element, String char_sequence) { 
    ((JavascriptExecutor) browser).executeScript("arguments[0].value='" + 
      char_sequence + "';", element); 
} 

public void send_keys_v2(WebElement element, String char_sequence) { 
    ((JavascriptExecutor) browser).executeScript("arguments[0].setAttribute=('value', '" + 
      char_sequence + "');", element); 
} 

參考文獻:Set value of input instead of sendKeys() - selenium webdriver nodejs

How can I consistently remove the default text from an input element with Selenium?

回答

1

一個可能的和可能的答案是,你有另一個同名的元素,在你試圖清除的那個之前。

請檢查html,並檢查,如果找到多個元素,然後第一個被採取。

作爲替代方案,你可以使用一個CSS選擇器,如:

.searchInput[name*=search_distance]

1

嘗試在硒的使用方法:

WebElement.clear()

無效明確()如果此元素是一個文本輸入元件,這將清除 的值。對其他元素沒有影響。文本輸入元素是 INPUT和TEXTAREA元素。 More info here