CasperJS/SpookyJS css 选择器存在但不存在

CasperJS/SpookyJS css selector is existing and not-existing

我在使用 spookyjs / capserjs 抓取屏幕时遇到一个奇怪的问题。

我想从以下网站获取信息:“https://www.rwe-smarthome.de/is-bin/INTERSHOP.enfinity/WFS/RWEEffizienz-SmartHome-Site/de_DE/-/EUR/ViewApplication-DisplayWelcomePage”。

因为该站点包含不止一页的产品我也想打开其他站点。

一般可以用

this.click(selector, function() {}); 

实现这一目标。

由于一些奇怪的原因,这在这里不起作用。

请看下面的代码:

var selector1 = "div#workingTemplate div:first-of-type ul.linkList li:nth-child(2) a";

spooky.waitUntilVisible(selector1);
spooky.thenClick(selector1);
spooky.wait(500);
spooky.then(function() {
    this.capture("RWETest-02.jpg");
});

我收到一条错误消息

CasperError: Cannot dispatch mousedown event on nonexistent selector: div#workingTemplate div:first-of-type ul.linkList li:nth-child(2) a

这很奇怪,因为如果选择器/DOM 对象不存在,它应该在 waitUntilVisible() 处失败。

此外,当我尝试检查选择器是否存在时,答案似乎是肯定的,因为我也遇到了选择器不存在的错误:

代码:

spooky.then([{sel: selector1},function() {
    if(this.exists(sel)) {
        this.click(sel);
        this.wait(500);
        this.then(function() {
            this.capture("RWETest-02.jpg");
        });
    }
    else {
        this.emit("logMessage", "Selector does not exists...");
    }
}]);

错误:

CasperError: Cannot dispatch mousedown event on nonexistent selector: div#workingTemplate div:first-of-type ul.linkList li:nth-child(2) a

因为 SpookyJS,我使用 PhantomJS 1.9.7 和 CasperJS 1.1.0-beta3。

有人对此有想法吗?

这很可能与 PhantomJS 1.x 中的错误有关,该错误无法根据使用 :nth-child() 的 CSS 选择器正确查找元素。有关详细信息,请参阅

由于 CasperJS 的几乎所有函数都支持 XPath 表达式,您可以将 CSS 选择器转换为 XPath 表达式:

var xpathExpr1 = "//div[@id='workingTemplate']//div[1]//ul[contains(@class,'linkList')]//li[2]//a";

然后你可以像这样使用它:

var selectXPath = 'xPath = function(expression) {
  return {
    type: "xpath",
    path: expression,
    toString: function() {
      return this.type + " selector: " + this.path;
    }
  };
};'
...
spooky.then([{x: selectXPath}, function() {
    eval(x);
    this.waitUntilVisible(xPath(xpathExpr1));
    this.thenClick(xPath(xpathExpr1));
    ...
]);

问题是 SpookyJS 不公开 XPath 实用程序,因此您需要做一些 in GitHub isse #109.

中描述的解决方法