Set value of input instead of sendKeys() - Selenium WebDriver nodejs

后端 未结 8 1892
死守一世寂寞
死守一世寂寞 2020-11-30 03:53

I have a long string to test and sendKeys() takes too long. When I tried to set the value of the text the program crashes. I know the Selenium

相关标签:
8条回答
  • 2020-11-30 04:06
    JavascriptExecutor js = (JavascriptExecutor)driver;
    js.executeScript("document.querySelector('attributeValue').value='new value'");
    
    0 讨论(0)
  • 2020-11-30 04:13

    Thanks to Andrey-Egorov and this answer, I've managed to do it in C#

    IWebDriver driver = new ChromeDriver();
    IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
    string value = (string)js.ExecuteScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");
    
    0 讨论(0)
  • 2020-11-30 04:15

    An alternative way of sending a large number of repeating characters to a text field (for instance to test the maximum number of characters the field will allow) is to type a few characters and then repeatedly copy and paste them:

    inputField.sendKeys('0123456789');
    for(int i = 0; i < 100; i++) {
        inputField.sendKeys(Key.chord(Key.CONTROL, 'a'));
        inputField.sendKeys(Key.chord(Key.CONTROL, 'c'));
        for(int i = 0; i < 10; i++) {
            inputField.sendKeys(Key.chord(Key.CONTROL, 'v'));
        }
    }
    

    Unfortunately pressing CTRL doesn't seem to work for IE unless REQUIRE_WINDOW_FOCUS is enabled (which can cause other issues), but it works fine for Firefox and Chrome.

    0 讨论(0)
  • 2020-11-30 04:18

    In a nutshell, this is the code which works for me :)

    WebDriver driver;
    WebElement element;
    String value;
    
    JavascriptExecutor jse = (JavascriptExecutor)driver;
    jse.executeScript("arguments[0].value='"+ value +"';", element);
    
    0 讨论(0)
  • 2020-11-30 04:24

    Try to set the element's value using the executeScript method of JavascriptExecutor:

    WebDriver driver = new FirefoxDriver();
    JavascriptExecutor jse = (JavascriptExecutor)driver;
    jse.executeScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");
    
    0 讨论(0)
  • 2020-11-30 04:25

    Thanks to Andrey Egorov, in my case with python setAttribute not working, but I found I can set the property directly,

    Try this code:

    driver.execute_script("document.getElementById('q').value='value here'")
    
    0 讨论(0)
提交回复
热议问题