使用 PhantomJS 选择菜单项

Selecting menu item using PhantomJS

我有简单的 PhantomJS 脚本来将网站的 Javascript 内容解析为 html。 (然后使用其他工具从 html 代码中提取一些数据。)

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 并且可能无法在其上运行:)

由于页面有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
});

可以直接调用该页面底层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 solution中复制粘贴了一部分