Selenium WebDriver C#:查找文本输入元素时引发异常

问题描述

<div class="_5yk2" tabindex="-1"><div class="_5rp7"><div class="_1p1t" style=""><div class="_1p1v" id="placeholder-7mj5h" style="white-space: pre-wrap;">Write a post...</div></div><div class="_5rpb"><div aria-autocomplete="list" aria-controls="js_fe" aria-describedby="placeholder-7mj5h" aria-label="Write a post..." aria-multiline="true" class="notranslate _5rpu" contenteditable="true" role="textBox" spellcheck="true" style="outline: none; user-select: text; white-space: pre-wrap; overflow-wrap: break-word;"><div data-contents="true"><div class="" data-block="true" data-editor="7mj5h" data-offset-key="6o271-0-0"><div data-offset-key="6o271-0-0" class="_1mf _1mj"><span data-offset-key="6o271-0-0"><br data-text="true"></span></div></div></div></div></div></div></div>

我正在Chrome驱动程序中使用XPath查找文本区域。这是我的代码行。

ele = driver.FindElement(By.XPath("//div[@aria-autocomplete='list']"));

Chrome驱动程序引发NoSuchElementException。如何获取此元素,以便可以向其中发送文本?

解决方法

要找到文本输入WebElement,必须为所需的ElementToBeClickable()引入 WebDriverWait ,并且可以使用以下任一Locator Strategies

  • CssSelector

    IWebElement element = new WebDriverWait(driver,TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("div[aria-autocomplete='list'][aria-describedby^='placeholder'][aria-label='Write a post...']")));
    
  • XPath

    IWebElement element = new WebDriverWait(driver,TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[@aria-autocomplete='list' and starts-with(@aria-describedby,'placeholder')][@aria-label='Write a post...']")));