2016-11-25 77 views
14

我使用phantomJS,我想從html網頁選擇元素。PhantomJS - 選擇html元素

這是我在phantomJS代碼:

var page = require('webpage').create(); 
var url = 'http://localhost:9001/build/browser/index.html'; 

page.open(url, function (status) { 
    if (status === 'success') { 
    var input = page.evaluate(function() { 
     return document.querySelector('[fill="#ffcc00"]'); 
    }, 2000); 
    console.log(input); 
    phantom.exit(); 
    } 
}); 

這裏是我的html:

<html lang="en-US" class=" js "> 
    <head> 
    </head> 
    <body> 
     <section class="mapSection"> 
      <article id="mainMap"> 
       <div id="map" class="leaflet1" > 
        <div class="leaflet2" > 
         <div class="leaflet3"> 
          <div class="leaflet4"> 
           <svg class="leaflet5" > 
            <g> 
             <path stroke="#000000" fill="#ffcc00" class="leaflet6" ></path> 
            </g> 
           </svg> 
          </div> 
         </div> 
        </div> 
       </div> 
      </article> 
     </section> 
    </body> 
</html> 

如何選擇使用querySelector這個元素?

+2

檢查元件是否存在 – przemoinho

回答

12

您需要使用return !!document.querySelector('path[fill="#ffcc00"]')如果選擇器存在則返回true,否則返回false。

var page = require('webpage').create(); 
var url = 'http://localhost:9001/build/browser/index.html'; 

page.open(url, function (status) { 
    if (status === 'success') { 
    var input = page.evaluate(function() { 
     return !!document.querySelector('path[fill="#ffcc00"]'); // returns true if the selector is exist, otherwise false. 
    }, 2000); 
    console.log(input); 
    phantom.exit(); 
    } 
});