使用javascript链接下载PhantomJS [英] PhantomJS download using a javascript link
问题描述
我试图抓住以下网站:
如果您点击标题为导出数据的表格右上角的小按钮,则会运行一个javascript脚本,我的浏览器以.csv格式下载文件。我希望能够编写一个可以自动执行此操作的PhantomJS脚本。有什么想法吗?
If you click the small button at the top-right of the table titled "export data", a javascript script runs and my browser downloads the file in .csv form. I'd like to be able to write a PhantomJS script that can do this automatically. Any ideas?
上面的按钮被编码成HTML格式:
The above button is coded into HTML as such:
<a id="LB_cmdCSV" href="javascript:__doPostBack('LB$cmdCSV','')">Export Data</a></div>
我还在HTML源代码中找到了这个函数:
I also found this function in the HTML source code:
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
我是PhantomJS / Javascript的新手,可以在这里使用一些指针。我想我已经找到了我需要自动完成的所有信息(如果我错了,请纠正我),但不知道从哪里开始编码。感谢您的帮助。
I'm very new to PhantomJS/Javascript and could use some pointers here. I think I've found all the info I need to do this automatically (correct me if I'm wrong), but just not sure where to start on coding it. Thanks for any help.
编辑 - 这就是我的剧本现在的样子:
EDIT - This is what my script looks like right now:
var page = new WebPage();
url = 'http://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=0&type=8&season=2011&month=0&season1=2011&ind=0&team=0&rost=0& players=0';
page.open(encodeURI(url), function (status){
if (status !== "success") {
console.log("Unable to access website");
} else {
page.evaluate(function() {
__doPostBack('LB$cmdCSV', '');
});
}
phantom.exit(0);
});
推荐答案
对我来说效果很好的是模拟鼠标点击在期望的元素上。
What have worked very well for me is simulating mouse clicks on the desired element.
page.evaluate(function () {
var btn = document.getElementById('LB_cmdCSV')
var ev = document.createEvent('MouseEvent')
ev.initEvent('click', true, true)
btn.dispatchEvent(ev)
})
这篇关于使用javascript链接下载PhantomJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!