2015-12-16 27 views
2

我有簡單的PhantomJS腳本來解析Javascript網站的內容到html。 (有些數據隨後使用其他工具html代碼中提取。)使用PhantomJS選擇菜單項

var page = require('webpage').create(); 
var fs = require('fs');// File System Module 
var output = '/tmp/sourcefile'; // path for saving the local file 
page.open('targeturl', function() { // open the file 
    fs.write(output,page.content,'w'); // Write the page to the local file using page.content 
    phantom.exit(); // exit PhantomJs 
}); 

(我得到了這些代碼行從http://kochi-coders.com/2014/05/06/scraping-a-javascript-enabled-web-page-using-beautiful-soup-and-phantomjs/

這用來工作時所有目標有直接聯繫。現在,他們是同一個URL後面,有下拉菜單:

<select id="observation-station-menu" name="station" onchange="updateObservationProductsBasedOnForm(this);"> 
    <option value="101533">Alajärvi Möksy</option> 
    ...  
    <option value="101541">Äänekoski Kalaniemi</option> 
    </select> 

這是菜單項我真的喜歡加載:

<option value="101632">Joensuu Linnunlahti</option> 

因爲這個菜單的我的腳本只下載相關數據到默認位置。如何從菜單中加載其他項目的內容並下載該項目的內容html

我的目標網站是這樣的:http://ilmatieteenlaitos.fi/suomen-havainnot

(如果有一個以上PhantomJS這樣做,我可以使用它,以及更好的辦法我的興趣是在處理數據一旦得到它刮掉,我選擇了PhantomJS。 。只是因爲它是工作的第一件事情,因爲我的服務器是一個Raspberry Pi某些選項可能受到限制,可能無法在它的工作:Python Selenium: Firefox profile error

回答

1

你可以直接調用該函數,這是在該網頁上的基本JS定義:

var page = require('webpage').create(); 
var fs = require('fs');// File System Module 
var output = '/tmp/sourcefile'; // path for saving the local file 
page.open('targeturl', function() { // open the file 
    page.evaluate(function() { 
    updateObservationProducts(101632, 'weather'); 
    }); 
    window.setTimeout(function() { 
    fs.write(output,page.content,'w'); // Write the page to the local file using page.content 
    phantom.exit(); // exit PhantomJs 
    }, 1000); // Change timeout as required to allow sufficient time 

}); 

對於等待渲染,看到這個phantomjs not waiting for "full" page load,我複製粘貼從rhunwicks解決方案的一部分。

+0

這與其他答案類似。傳遞沒有錯誤,但包含默認選擇的數據。 –

+0

我更新瞭解決方案,也許是因爲這個原因。 – user5542121

+0

解決了它,謝謝! –

3

由於頁有jQuery的,你可以這樣做:

page.open('targeturl', function() { // open the file 
    page.evaluate(function() { 
    jQuery('#observation-station-menu').val('101632').change(); 
    }); //change the checkbox, then fires the event 
    fs.write(output,page.content,'w'); // Write the page to the local file using page.content 
    phantom.exit(); // exit PhantomJs 
}); 
+0

您的變體可能更好,因爲它會更容易更新我猜。 – user5542121

+0

我跑這個,但生成的文件仍然包含默認選擇的信息。從文件中:' ' –

+0

@MadocComadrin那麼,在改變數值和看到新圖像之間有一段延遲。您需要爲腳本添加延遲。 –