2013-08-19 38 views
16

當我嘗試放棄this site與Phantomjs,默認情況下,Phantomjs發送以下標題到服務器:假裝火狐,而不是Phantom.js

"name":"User-Agent", 
"value":"Mozilla/5.0 (Unknown; Linux i686) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.1 Safari/534.34"} 

我也得到一個status 405 "Not Allowed"響應。

我讀了Phantomjs API參考,爲了模仿來自其他瀏覽器的請求,我應該更改我的User-Agent值。在維基百科上,我發現我應該假裝火狐Ubuntu的使用值:

'name': 'User-Agent', 
'value': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:16.0) Gecko/20120815 Firefox/16.0' 

在我應該放什麼Phantomjs的一部分,這個屬性?我應該在哪裏插入它們 - 在page.open或內部page.evaluate,或在它的頂部?

回答

20

其實,在page.settings。在open之前執行此操作。

下面是使用它針對您鏈接該頁面的例子:

var page = require('webpage').create(); 
page.settings.userAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36'; 
page.open('http://www.oddsportal.com/baseball/usa/mlb/results/page/', function() { 
    window.setTimeout(function() { 
     var output = page.evaluate(function() { 
      return document.getElementById('tournamentTable') 
      .getElementsByClassName('deactivate')[0] 
      .getElementsByTagName('a')[0] 
      .textContent; 
     }); 
     console.log(output); 
    }, 1000); 
}); 

這個例子將刮在桌子上第一行的比賽名稱。 (在這個精確時刻是 「San Francisco Giants - Boston Red Sox」)


關於你的評論,其實你可以在phantomjs使用jquery!檢查這個例子:

var page = require('webpage').create(); 
page.settings.userAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36'; 
page.open('http://www.oddsportal.com/baseball/usa/mlb/results/page/', function() { 
    window.setTimeout(function() { 
     page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js", function() { 
      var output = page.evaluate(function() { 
       return jQuery('#tournamentTable .deactivate:first a:first').text(); 
      }); 
      console.log(output); 
     }); 
    }, 1000); 
}); 

順便說一句,等待,而不是我在這個例子中使用的window.setTimeout的,我建議你使用waitfor.js代替。

+0

謝謝了很多,在jQuery> sizzle之後很難用'getElementsByClassName'來玩 – khex

+2

@khaljava哦,但是你可以在幻影之下使用jquery,我只是沒有那麼簡單。檢查更新的答案。 –

+1

即使您設置了標題,某些網站也有辦法檢測PhantomJS,但它們會返回錯誤或空白屏幕。如果我在Chrome中打開它們,一切都很好。我想知道有沒有辦法來處理它 – Toolkit