使用PhantomJS选择菜单项

时间:2015-12-16 18:05:13

标签: javascript phantomjs html-select

我有简单的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/获得了这些代码行)

当所有目标都有直接链接时,这曾经有效。现在他们在同一个网址后面,有下拉菜单:

<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

2 个答案:

答案 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
});

答案 1 :(得分: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解决方案中复制粘贴了一部分。