Geb选择器未选择

ndu*_*eck 1 groovy selenium web-scraping geb

我注意到在某些情况下,geb选择器无法按预期工作。当我从开发人员控制台复制css selecor,css路径或xpath并将其用作geb中的选择器时,它们将无法工作。无论如何,在此示例中,我无法选择我想要的:

网站:https//money.cnn.com/data/fear-and-greed/

<div id="needleChart" style="background-image:url('//money.cnn.com/.element/img/5.0/data/feargreed/1.png');">
    <ul>
        <li>Fear & Greed Now: 72 (Greed)</li><li>Fear &amp; Greed Previous Close: 72 (Greed)</li>
        <li>Fear & Greed 1 Week Ago: 69 (Greed)</li><li>Fear &amp; Greed 1 Month Ago: 58 (Greed)</li>
        <li>Fear & Greed 1 Year Ago: 8 (Extreme Fear)</li>
   </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

现在,我想从第一个li-tag 获取文本,这是我的代码:

public class MoneyCnnFearAndGreed extends Page {
    static url = 'https://money.cnn.com/data/fear-and-greed'
    static content = {
        fearAndGreed { $("#needleChart").$("ul li")[0].text() }
    }
}

Browser.drive {
    to MoneyCnnFearAndGreed
    println fearAndGreed
}
Run Code Online (Sandbox Code Playgroud)

但是结果是空的。希望你能在这里帮助我。

kri*_*aex 5

您的ullist元素已隐藏,请参见相应的CSS文件

.feargreed #needleChart ul {
    visibility: hidden;
    height: 0;
    width: 0;
}
Run Code Online (Sandbox Code Playgroud)

Geb基于Selenium WebDriver,因此您无法与隐藏的内容进行交互,因为《 Geb书》明确指出:

我们想单击Geb链接,但不能单击,因为它是隐藏的(WebDriver不允许您与隐藏的元素进行交互)。

因此,除了通过在Spock / Geb测试中执行JS之外,您没有机会获得不可见元素的文本内容:

println js.exec("return document.querySelectorAll('#needleChart ul li')[0].textContent;")
Run Code Online (Sandbox Code Playgroud)