【发布时间】:2016-07-02 22:15:07
【问题描述】:
我想自动化访问网站、单击按钮和保存文件的过程。在此站点上下载文件的唯一方法是单击按钮。您无法使用 url 导航到文件。
我一直在尝试使用 phantomjs 和 casperjs 来自动化这个过程,但没有任何成功。
我最近在这里尝试使用布兰登的解决方案 Grab the resource contents in CasperJS or PhantomJS
这是我的代码
var fs = require('fs');
var cache = require('./cache');
var mimetype = require('./mimetype');
var casper = require('casper').create();
casper.start('http://www.example.com/page_with_download_button', function() {
});
casper.then(function() {
this.click('#download_button');
});
casper.on('resource.received', function (resource) {
"use strict";
for(i=0;i < resource.headers.length; i++){
if(resource.headers[i]["name"] == "Content-Type" && resource.headers[i]["value"] == "text/csv; charset-UTF-8;"){
cache.includeResource(resource);
}
}
});
casper.on('load.finished', function(status) {
for(i=0; i< cache.cachedResources.length; i++){
var file = cache.cachedResources[i].cacheFileNoPath;
var ext = mimetype.ext[cache.cachedResources[index].mimetype];
var finalFile = file.replace("."+cache.cacheExtension,"."+ext);
fs.write('downloads/'+finalFile,cache.cachedResources[i].getContents(),'b');
}
});
casper.run();
我认为问题可能是由于我在 cache.js 中的 cachePath 不正确
exports.cachePath = 'C:/Users/username/AppData/Local/Ofi Labs/PhantomJS';
除了反斜杠之外,我还应该使用其他东西来定义路径吗?
当我尝试时
casperjs --disk-cache=true export_script.js
没有下载任何内容。经过一点调试,我发现cache.cachedResources总是空的。
我也愿意接受 phantomjs/casperjs 之外的解决方案。
更新
我不再尝试使用 CasperJS/PhantomJS 来实现这一点。 我正在使用 dandavis 建议的 chrome 扩展 Tampermonkey。 Tampermonkey 非常容易破解。 我安装了 Tampermonkey,导航到带有下载链接的页面,然后单击 Tampermonkey 下的 New Script 并添加我的 javascript 代码。
document.getElementById("download_button").click();
现在,每次我在浏览器中导航到该页面时,都会下载该文件。然后我创建了一个看起来像这样的批处理脚本
set date=%DATE:~10,4%_%DATE:~4,2%_%DATE:~7,2%
chrome "http://www.example.com/page-with-dl-button"
timeout 10
move "C:\Users\user\Downloads\export.csv" "C:\path\to\dir\export_%date%.csv"
我使用 Windows 任务调度程序将该批处理脚本设置为每晚运行。
成功了!
【问题讨论】:
-
tampermonkey 是一种在访问某个页面时单击按钮的简单方法。 window 的计划任务是按计划打开 url 的好方法:只需运行 url 或指定并运行例如。
chrome.exe 'http://example.com'什么的。您也可以运行快捷方式文件...无论如何,浏览器会打开该页面,然后 Tampermonkey 单击按钮。一直在很少使用的桌面上使用它。 -
使用selenium wedriver,看这个链接yizeng.me/2014/05/23/…
-
谢谢!我从来没有听说过tampermonkey。
-
你可能应该移动你的事件处理程序之前
casper.start() -
反斜杠需要转义!
exports.cachePath = 'C:\\Users\\username\\AppData\\Local\\Ofi Labs\\PhantomJS';,不过windows也支持正斜杠exports.cachePath = 'C:/Users/username/AppData/Local/Ofi Labs/PhantomJS';
标签: javascript csv automation phantomjs casperjs