【问题标题】:Selenium find hidden element C#Selenium 查找隐藏元素 C#
【发布时间】:2016-03-11 07:19:12
【问题描述】:

我有特定的情况,从谷歌浏览器的 Inspect 元素我有这个:

 <span class="markup--quote markup--p-quote is-other" name="anon_7ee3d25bf521" data-creator-ids="anon">If what you care about&#8202;—&#8202;or are trying to report on&#8202;—&#8202;is impact on the world, it all gets very slippery. You’re not measuring a rectangle, you’re measuring a multi-dimensional space. You have to accept that things are very imperfectly measured and just try to learn as much as you can from multiple metrics and anecdotes.</span>

我想获取基于data-creator-ids="anon" 的文本,但问题是当我单击查看页面源时,这完全隐藏了。

我试试这个:

IWebElement ell = driver.FindElement(By.CssSelector("[data-creator-ids='anon']"));

            MessageBox.Show(ell.GetAttribute("innerHTML"));

问题:

OpenQA.Selenium.NoSuchElementException 未处理
HResult=-2146233088 消息=没有这样的元素:无法定位 元素:{“方法”:“css selector","selector":"[data-creator-ids='anon']"} (会话信息: chrome=48.0.2564.116)(驱动程序信息:chromedriver=2.21.371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4),平台=Windows NT 10.0 x86_64) 源=WebDriver

我也尝试了类名,但同样的问题。 获取此文本有什么技巧吗?

我也有一个按钮有同样的问题,我只需要 Id 但按钮完全隐藏在 html 源代码中:

<button class="button button--chromeless" data-action="select-anchor" data-action-value="3331">Top highlight</button>

【问题讨论】:

  • 有问题的元素总是跨度吗?
  • 是的,它总是跨度
  • 元素是否加载了 ajax ?也许你需要在定位元素之前添加一些wait
  • 我尝试了答案中给出的两种解决方案,都对我有用....

标签: c# selenium selenium-chromedriver


【解决方案1】:

如果您查看this interesting post,您会注意到在使用 CSS-Selectors 时需要定义元素类型:

element[attribute(*|^|$|~)='value']

基于此,您所要做的就是将正确的元素添加到您的选择器;在你的情况下一个跨度元素:

IWebElement ell = driver.FindElement(By.CssSelector("span[data-creator-ids='anon']"));
MessageBox.Show(ell.GetAttribute("innerHTML"));

因此,您应该使用"span[data-creator-ids='anon']" 而不是"[data-creator-ids='anon']"。这应该会产生正确的结果。

【讨论】:

  • WebDriver.dll 中出现“OpenQA.Selenium.NoSuchElementException”类型的未处理异常附加信息:没有这样的元素:无法找到元素:{“method”:“css selector”,“selector” :"span[data-creator-ids='anon']"}
  • 页面上没有具有 data-creator-ids=anon 属性的元素......
  • 是的,在 html 源代码中没有,但您可以在 Google Chrome 的检查元素中看到它。
  • 即使使用简单的 document.getElementsByTagName 也不会显示跨度存在。我也无法使用 Chromes Inspect Element 找到它...
【解决方案2】:

尝试通过 XPath 而不是 CSSSelector 可能会更好。这可能会让你更近一步:

IWebElement ell = driver.FindElement(By.XPath("//span[@data-creator-ids='anon']"));

【讨论】:

  • WebDriver.dll 中发生了“OpenQA.Selenium.NoSuchElementException”类型的未处理异常附加信息:没有这样的元素:无法找到元素:{“method”:“xpath”,“selector”: "//span[@data-creator-ids='anon']"}
  • 会在一小时内回复你——学校运行:)。查看页面源。 data-creator-ids 不在场 - 很快回来...
  • 大声笑-或不(基于偷偷摸摸的-1票)..哈哈哈!! (e4xplode) :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 2012-08-15
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多