遍历HTML页面元素
PhantomJS Iterating through HTML page elements
有人能帮我解决这个问题吗?
我正在用PhantomJS抓取本地HTML文件,我试图在屏幕上显示类"test"的HTML标签的内容。我确实得到了第一个标签的内容,但不知怎么的,我没有得到下一个标签的内容。
-= HTML/index.html =-
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="parent-id">
<p>hello word 1</p>
<p class="test">hello word 2</p>
<p class="test">hello word 3</p>
<p>hello word 4</p>
</div>
</body>
</html>
-= PhantomJS/test2.js =-
var fs = require('fs');
var page = require('webpage').create();
page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:49.0) Gecko/20100101 Firefox/49.0';
page.viewportSize = {width:1200, height:1024};
page.onConsoleMessage = function (msg) {
//console.log(msg);
}
page.open('http://localhost/index.html', function(status) {
if (status == 'success') {
var products = page.evaluate(function() {
return document.getElementsByClassName('test')
});
for(var i = 0; i < products.length; ++i) {
if(products[i]) {
console.log(products[i].innerHTML);
}
}
phantom.exit();
} else {
console.log('Unable to load the address!');
phantom.exit();
}
});
当我运行phantomjs "test2.js"时,我得到:
hello word 2
而我期望得到:
hello word 2
hello word 3
您不应该从页面上下文返回元素。返回简单值。这个例子适用于您的index.html:
page.open('http://localhost/index.html', function(status) {
if (status == 'success') {
var products = page.evaluate(function() {
return [].map.call(document.getElementsByClassName('test'), function(elem) {
return elem.innerHTML;
});
});
for(var i = 0; i < products.length; ++i) {
if(products[i]) {
console.log(products[i]);
}
}
phantom.exit();
} else {
console.log('Unable to load the address!');
phantom.exit();
}
});
相关文章:
- 我应该怎么做才能避免在网页上移动元素(html、css、jQuery)
- 更改元素HTML,但忽略最后一个子项
- 增加在选择元素HTML中搜索的时间
- Jquery无法获取元素html
- 从所选元素 html 上方的元素获取属性值
- 在 JS 的单选按钮元素 (HTML) 中使用 title 属性
- 如何在页面上播放每个音频元素(HTML,JQuery,Javascript)
- 我需要一种新的方法来检测元素 HTML 是否有更改
- 获取父元素 html 以及子内容
- AngularJS指令:如何在ng-repeat中动态更改元素html
- html 属性中的引号被标记为 ”来自元素.html()的结果
- 在指令's链接中替换angular元素html
- 如果元素有子元素html元素
- 如何下推表格中的元素- HTML
- 如何在纯javascript中使用变量插入数组值,如元素HTML
- jQuery textilate .js -如何“重置”元素HTML并重新启动动画
- 将元素HTML附加到新附加的textarea中
- 在添加类的情况下,CSS 3的过渡是否不能与模板元素(HTML 5)一起工作?
- jQuery没有更新DOM元素HTML
- 在jQuery中更快地替换元素HTML