誰でもこの問題を助けてくれますか?PhantomJS HTMLページ要素を反復する
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
問題がphantomjs – Mahi
@Amonであるあなたは、 'はconsole.log(document.getElementsByClassName( 'テスト'))追加してみました;'あなたのreturn文をいただきました!参照してくださいする前に返されますか? – user3366016
@Amonまた、あなたの評価関数にあなたのforループを移動してそこに変数を保存してみてください。 forループを使用するこの例のほうがよく似ています。 https://www.sitepoint.com/web-crawling-node-phantomjs-horseman/ 'page.evaluate(function(){var products = document.getElementsByClassName( 'test'); for(var i = 0; i < – user3366016