问题
I am getting this error while trying to write to simple code in selenium webdriver to enter a value in google search page and enter. Following is my code -:
WebDriver driver = new FirefoxDriver(profile);
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.get("http://www.google.com");
WebElement element=driver.findElement(By.xpath("//input[@id='gs_htif0']"));
boolean b = element.isEnabled();
if (b){
System.out.println("Enabled");
}
element.sendKeys("Test Automation");
element.submit();
Can anyone please help me out with this? How to enable a disabled element?
回答1:
You are using the wrong 'input' for entering the text. You should be using the following XPath:
//input[@name='q']
Like
WebElement element=driver.findElement(By.xpath("//input[@name='q']"));
This 'input' element accepts the input text just fine.
回答2:
You can try to run javascript on page:
((JavascriptExecutor) driver).executeScript("document.getElementById('gs_htif0').disabled = false");
or
((JavascriptExecutor) driver).executeScript("arguments[0].disabled = false", element);
回答3:
See, if this might help,
WebDriver driver = new FirefoxDriver(profile);
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.name("q"));
if(element.isEnabled()) {
System.out.println("Enabled");
element.sendKeys("Test Automation");
element.submit();
}
回答4:
Try this:
WebDriverWait wait = new WebDriverWait(driver, 40);
driver.get("http://www.google.com");
wait.until(ExpectedConditions.visibilityOfElementLocated(By
.xpath("//input[@id='gs_htif0']")));
driver.findElement(By.xpath("//input[@id='gs_htif0']"))
.sendKeys("Test Automation" + Keys.ENTER);
Or:
public boolean isElementPresent(WebDriver driver, By by)
{
try {
driver.findElement(by);
System.out.print("Enabled");
return true;
} catch (NoSuchElementException ignored) {
return false;
}
}
isElementPresent = isElementPresent(
driver, By.xpath("//input[@id='gs_htif0']"));
if (isElementPresent) {
element.sendKeys("Test Automation");
element.submit();
}
Or change xPath to name selector.
回答5:
If i am correct then you are using the firebug add-on in the firefox driver to get the path for the searchbox. But the firebug seems to provide a path where the Id for the searchbox is not correct. If you use the inspect element option you can see the difference (in the below image you can spot the difference yourself).
来源:https://stackoverflow.com/questions/20772696/selenium-webdriver-org-openqa-selenium-invalidelementstateexception-element-is