Selenium 查找隐藏元素 C#

Selenium find hidden element C#

我有具体情况,来自 Google Chrome 中的 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 was unhandled
HResult=-2146233088 Message=no such element: Unable to locate element: {"method":"css selector","selector":"[data-creator-ids='anon']"} (Session info: chrome=48.0.2564.116) (Driver info: chromedriver=2.21.371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4),platform=Windows NT 10.0 x86_64) Source=WebDriver

我也试过 Class Name 但同样的问题。 获取此文本有什么技巧吗?

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

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

如果您看一下 this interesting post,您会注意到在使用 CSS-选择器时需要定义一个元素类型:

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

基于此,您所要做的就是将正确的元素添加到您的选择器中;在你的例子中是一个 span 元素:

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']"。这应该会产生正确的结果。

尝试通过 XPath 获取可能比 CSSSelector 更好。这可能会让您更进一步:

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