2014-07-10 105 views
0

我在这里获得HTML代码。选择标记ID

在浏览器中,我能卖到使用Firebug每个ID喜欢

document.querySelectorAll('section').item(0).id 

这意味着,如果我做一个变量

inputFields = this.evaluate(function() { 
    return document.getElementsByTagName('section'); 
}); 

所以inputFields阵列应该有他们的ID的所有四个部分。稍后,我可以使用inputFields.item(index).id来访问它,指向任何节ID。

这里是我的卡斯帕脚本:

casper.then(function(){ 
    var inputFields = this.evaluate(function(){ 
     return document.getElementsByTagName('section'); 
    }); 
    require("utils").dump(inputFields.item(1).id); 
}); 

请纠正我,如果我做错了什么。我得到的错误:

error: 'undefined' is not a function (evaluating 'inputFields.item(1)') 
#   TypeError: 'undefined' is not a function (evaluating 'inputFields.item(1)') 

我想有一个节ID的数组。

+0

我的回答有帮助吗,你有什么问题吗? –

回答

0

您无法从页面上下文中将DOM元素检索到casper上下文中。只允许像布尔,数字,字符串,[]{}等原始类型。从PhantomJS documentation的报价是这样的:

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine. Closures, functions, DOM nodes, etc. will not work!

你需要做的页面上下文你的工作的一部分。像只减少了元件的id

casper.then(function(){ 
    var inputFields = this.evaluate(function(){ 
     return Array.prototype.map.call(document.getElementsByTagName('section'), function(sectionItem){ 
      return sectionItem.id; 
     }); 
    }); 
    require("utils").dump(inputFields[1]); 
}); 

虽然,我不认为这类型section你的情况输入字段。您可能是指某个部分内的输入字段。