Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript CasperJS/SpookyJS css选择器存在且不存在_Javascript_Css Selectors_Web Scraping_Phantomjs_Spookyjs - Fatal编程技术网

Javascript CasperJS/SpookyJS css选择器存在且不存在

Javascript CasperJS/SpookyJS css选择器存在且不存在,javascript,css-selectors,web-scraping,phantomjs,spookyjs,Javascript,Css Selectors,Web Scraping,Phantomjs,Spookyjs,我在使用spookyjs/capserjs进行屏幕抓取时遇到了一个奇怪的问题 我想从以下网站捕获信息:“” 因为该网站包含多个产品页面,所以我也想打开其他网站 通常人们可以使用 this.click(selector, function() {}); 为了实现这一点 出于某些奇怪的原因,这在这里不起作用 请查看以下代码: var selector1 = "div#workingTemplate div:first-of-type ul.linkList li:nth-child(2) a";

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

我想从以下网站捕获信息:“”

因为该网站包含多个产品页面,所以我也想打开其他网站

通常人们可以使用

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中的一个bug有关,该bug没有正确地根据使用
: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实用程序,因此您需要做一些描述的变通方法。

太好了,非常感谢!对于任何使用Webstorm和此解决方案的人来说,selectXPath必须放在一行中,否则将出现错误。