【问题标题】:Selenium WebDriver C#: Exception thrown finding text input elementSelenium WebDriver C#:查找文本输入元素时抛出异常
【发布时间】:2021-01-08 04:27:55
【问题描述】:
<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。如何获取此元素以便向其发送文本?

【问题讨论】:

  • 确保它不在 iframe 中。

标签: c# selenium xpath css-selectors webdriverwait


【解决方案1】:

要查找文本输入 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...']")));
    

【讨论】:

  • 我必须安装 Selenium.Support 才能使用 ExpectedCondition 并且它可以编译但已弃用。我发现我不能使用和开始(@aria- describeby,'placeholder'),因为每次运行代码时占位符都会更改(即 placeholder-c0g2a)。所以新代码是IWebElement element = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[@aria-autocomplete='list'][@aria-label='Write a post...']")));
  • 但我仍然收到错误 NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@aria-autocomplete ='list'][@aria-label='写一篇文章...']"}请告知DebanjanB
猜你喜欢
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 2018-07-14
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多