0

我陷入了这个问题:我们的网页有一个动态表,它将在div元素上加载值(学生的分数)。如果我们点击 said div,一个新的子元素input将被附加到div并且我们应该能够使用SendKeys方法输入一个新的标记。但是,当我尝试发送密钥时,会StaleElementReferenceException出现一个。

这是input添加时的元素(必须使用断点,因为一旦div元素失去焦点,元素就会消失):


<tr>
    <td class="indice">1</td>
    <td id="accion-1-alumno-0" data-tooltip="" title="Bustos, Guido" class="has-tip titulo">Bustos, Guido</td>
    <td data-tooltip="" title="1º ESA" class="has-tip titulo">1º ESA</td>
    <td class="nota relative  media noeditable k-nivel2_tabla" style="text-align:center; color: #ed1c24!important">
        <div id="accion-1-celda-0-0-0" class="elemento comentarios">2,00</div>
    </td>
    <td class="nota relative " style="text-align:center; color: #ed1c24!important">
        <div id="accion-1-celda-1-0-0" class="elemento comentarios">
            <input id="editor" type="text" value="2" maxlength="7">
        </div>
    </td>
    <td class="nota relative " style="text-align:center; color: #000000!important">
        <div class="elemento comentarios">
            <span id="accion-1-editar-2-0" class="block left ellipsis span  comentario" title=""></span>
            <span id="accion-1-prismaticos-2-0" class="glyphicons glyph_observaciones observacion right"></span>
        </div>
    </td>
</tr>

这是我用来单击div并尝试的代码SendKeys


IWebElement inputNota = SeleniumHelper.FindByXPath("//td[text() = '"+ nombreAlumno +"']/following-sibling::td/div[contains(@id, 'accion-1-celda')]");

SeleniumHelper.Click(inputNota);

SeleniumHelper.SendKeys(inputNota.FindElement(By.Id("editor")), nota);

谢谢你的时间

4

2 回答 2

1

如果将新元素附加到 html,则意味着 DOM 已刷新,或者至少是<div>, 因此driver“丢失”了先前定位的元素。你需要重新定位它

string locator = "//td[text() = '"+ nombreAlumno +"']/following-sibling::td/div[contains(@id, 'accion-1-celda')]";

IWebElement inputNota = SeleniumHelper.FindByXPath(locator);

SeleniumHelper.Click(inputNota);

SeleniumHelper.SendKeys(SeleniumHelper.FindByXPath(locator).FindElement(By.Id("editor")), nota);
于 2018-07-31T13:49:08.240 回答
0

当元素从 DOM 中删除/更改时,会发生 StaleElement。在任何情况下,您都需要重新抓取该元素。一个很好的方法是这样......

public static IWebElement HardFindElement(IWebDriver driver, By by)
    {
        IWebElement elementToReturn = null;

        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
        wait.Until(drv =>
        {
            try
            {
                elementToReturn = driver.FindElement(by);
                return true;
            }
            catch
            {

                return false;
            }
        });

        return elementToReturn;
    }

这将等待最多 30 秒,直到它能够从 DOM 中重新获取元素。您需要在单击后执行此操作以相应地重新初始化元素

于 2018-07-31T14:22:52.657 回答