Javascript 使用PhantomJS选择菜单项
我有一个简单的Javascript 使用PhantomJS选择菜单项,javascript,phantomjs,html-select,Javascript,Phantomjs,Html Select,我有一个简单的PhantomJS脚本将Javascript网站内容解析为html。(然后使用其他工具从html代码中提取一些数据。) (我从中获得了这些代码行) 在所有目标都有直接链接的情况下,这种方法通常有效。现在,它们位于同一url后面,并且有下拉菜单: <select id="observation-station-menu" name="station" onchange="updateObservationProductsBasedOnForm(this);"> <
PhantomJS
脚本将Javascript
网站内容解析为html
。(然后使用其他工具从html
代码中提取一些数据。)
(我从中获得了这些代码行)
在所有目标都有直接链接的情况下,这种方法通常有效。现在,它们位于同一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>
JoensuLinnunlahti
由于此菜单,我的脚本仅下载与默认位置相关的数据。如何从菜单中加载其他项目的内容并下载该项目的html
内容
我的目标站点是:
(如果有比
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
});
对于等待渲染,请参见此,我从Rhuncks解决方案复制粘贴了一个零件。您的变体可能更好,因为我想它更容易更新。我运行了此操作,但生成的文件仍然包含默认选择的信息。从文件:
Helsinki Kaisaniemi
@Madocomadrin嗯,duh,在更改值和查看新图像之间存在延迟。您需要在脚本中添加延迟。这与另一个答案的作用类似。传递的数据没有错误,但包含默认选择的数据。
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
});