NoSuchElementException-无法找到元素

Bim*_*esh 2 selenium-webdriver

我有一个输入框,例如我在这里用来输入问题的输入框,其HTML是

<body id="tinymce" class="mce-content-body" contenteditable="true" onload="window.parent.tinymce.get('Description').fire('load');" spellcheck="false" style="padding-bottom: 50px; padding-left: 1px; padding-right: 1px; overflow-y: hidden;">
<p>
<br data-mce-bogus="1"/>
</p>
</body>
Run Code Online (Sandbox Code Playgroud)

每次我都尝试输入一些文字

@FindBy(xpath="//body[@id='tinymce']") WebElement Category_Body;
Category_Body.sendKeys("Android Smart Phone - 16GB");
Run Code Online (Sandbox Code Playgroud)

我得到了错误-

org.openqa.selenium.NoSuchElementException:无法找到元素:{“ method”:“ xpath”,“ selector”:“ // body [@ id ='tinymce']”}

Sau*_*aur 6

如果您NoSuchElementException作为提供的例外,可能有以下原因:-

  • 可能是当您要查找元素时,它不会出现在上DOM,因此您应该实施WebDriverWait以等待元素可见,如下所示:-

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement Category_Body = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("tinymce")));
     Category_Body.sendKeys("Android Smart Phone - 16GB");
    
    Run Code Online (Sandbox Code Playgroud)
  • 可能是此元素位于任何frame或中iframe。如果是的话,您需要进行切换frameiframe在找到以下元素之前:-

    WebDriverWait wait = new WebDriverWait(driver, 10);
    
    //Find frame or iframe and switch
    wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("your frame id or name"));
    
    //Now find the element 
    WebElement Category_Body = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("tinymce")));
     Category_Body.sendKeys("Android Smart Phone - 16GB");
    
    //Once all your stuff done with this frame need to switch back to default
    driver.switchTo().defaultContent();
    
    Run Code Online (Sandbox Code Playgroud)