javascript - CasperJS/SpookyJS css 选择器存在且不存在

标签 javascript css-selectors web-scraping phantomjs spookyjs

我在使用 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 选择器正确查找元素。请参阅this question了解更多信息。

由于 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所述。 .

关于javascript - CasperJS/SpookyJS css 选择器存在且不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30684007/

相关文章:

javascript - 如何从基于 Javascript 的网络应用程序录制音频?

javascript - 减去两个 HTML 字段并尽快显示结果 JavaScript

javascript - Angularjs:如何将输入值传递给函数?

jQuery 匹配模式

python - 无法解析应用条件语句的某些信息

java - Jsoup:如何获取与特定类关联的所有 href

javascript - 缩小嵌入到 .html 文件中的 JS

html - 兄弟选择器 * + * 和 * ~ * 背后的逻辑是什么?

css - 如何将 CSS 分配给具有特定扩展名、高度和宽度的图像?

java - 使用 HtmlUnit 时出错