2017-03-19 22 views
0

解決此問題需要我很多時間。下面 是我phantomjs代碼phantomjs getElementsByClass()在評估中無法獲取元素

var page = require('webpage').create() 

page.open("https://www.google.com.hk/",function(status){ 
    if(status === 'success'){ 
     var aa = page.evaluate(function() { 
      return document.getElementsByClassName('ctr-p').length 
     }) 
     console.log(aa) 
    } 
    phantom.exit(0) 
}) 

正如你所看到的,在評價函數的返回值document.getElementsByClassName(「CTR-P」)的長度,當我將其複製到Chrome檢查控制檯,將打印「3 ',如下圖所示: enter image description here 但是當我執行phantomjs代碼時,結果爲'0'! enter image description here

這是什麼問題?請〜

回答

3

谷歌公司PhantomJS」默認用戶代理,並認爲它是某種過時的手機瀏覽器:

enter image description here

添加現代的用戶代理將解決這一問題。另請參閱下面的代碼示例爲其他建議:

var page = require('webpage').create() 

// Let's pretend we're Chrome 51 
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'; 

page.open("https://www.google.com.hk/",function(status){ 
    if(status === 'success'){ 
     var aa = page.evaluate(function() { 
      return document.getElementsByClassName('ctr-p').length 
     }) 
     console.log(aa) 

     // Make screenshots often to confirm 
     // everything is what you're thinking it is 
     page.render("googlehk.jpg"); 

     phantom.exit() // 0 = success exit code 
    } 
    else { 
     phantom.exit(1); // 1 = error exit code 
    } 


}) 
+0

對不起,延遲迴復。我將所有的代碼複製到我的Mac上,但也如上所示顯示0。 page.settings.userAgent ='Mozilla/5.0(Windows NT 6.1; WOW64)AppleWebKit/537.36(KHTML,像Gecko)Chrome/51.0.2704.106 Safari/537.36'唯一的好處是它不會顯示一些惱人的提示,如: https ://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/protocol/https/voice/js/voice_1e62c0f.js:23支持 等 – suoyong

+0

但你們給我一些建設性的意見,謝謝。 – suoyong

+0

謝謝。什麼是您的PhantomJS版本?可能會老了。 – Vaviloff

0

所以我給一些建議供phantomjs的初學者。如果你想在網站上通過phantomjs獲取元素。你必須檢查你的網站是否被訪問過登錄。 大多數網站將根據您的瀏覽器cookie登錄默認。但使用幻影,它並不是。原因是你沒有設置cookie。這就是爲什麼我的問題來到這裏。