2015-04-05 41 views
1

我正在研究一個項目,在這個項目中循環訪問一系列發票並從每張發票中提取數據表。我正在使用CasperJS編寫代碼,並且已經達到了可以將所有相關信息刪除並將其存儲在一個數組中的程度,但是無法將信息輸出到結構化的Excel中。CasperJS:將刮取的數據導出到結構化的Excel或CSV

代碼工作現在的方法如下:
1)捕獲每張發票
2的URL)貫穿於各個環節的循環和捕捉如發票號碼,發票日期,每個購買的產品名稱關鍵信息,以及每件產品的價格。

這裏是在這部分代碼看起來像:

function getDescriptions() { 
    var description = document.querySelectorAll('#InvoiceDetailGrid tbody tr td:nth-child(3)'); 
    return Array.prototype.map.call(description, function(elem) { 
    return elem.textContent; 
    }); 
} 

function getPrices() { 
    var price = document.querySelectorAll('#InvoiceDetailGrid tbody tr td:nth-child(4)'); 
    return Array.prototype.map.call(price, function(elem) { 
    return elem.textContent; 
    }); 
} 

casper.then(function() { 
    for(var z = 0; z < 5; z++) { 
    casper.thenOpen(baseURL + links[z]); 

    this.wait(2000, function() { 
     invoiceNumber = invoiceNumber.concat(this.fetchText('#InvoiceNumber')); 
     invoiceDate = invoiceDate.concat(this.fetchText(x('//*[@id="printArea"]/table/tbody/tr[1]/td/table/tbody/tr/td[1]/table/tbody/tr[2]/td[2]'))); 

     description = description.concat(this.evaluate(getDescriptions)); 
     price = price.concat(this.evaluate(getPrices)); 
    }); 
    } 
}); 

輸出是正確的,會是這個樣子:invoiceNumber = 1,2,3; invoiceDate = 2015年1月1日,2015年1月2日,2015年1月3日;描述=產品X,產品Y,產品X,產品Z,產品A,產品B,產品C;價格= 1美元,2美元,1美元,3美元,4美元,5美元,10美元。我想把這個數據看起來像這樣的表:

發票號碼發票日期描述價格
1 2015年1月1日產品X $ 1
1 2015年1月1日產品Y $ 2
1月2日2 2015年產品X $ 1
2 2015年1月2日產物Z $ 3
3 2015年1月3日產品A $ 4
3 2015年1月3日產品B $ 5
3 2015年1月3日產品C $ 10

每個invoiceNumber和invoiceDate w應與多種描述和價格相關聯,並且我想確保維持這種關係(如表中所示)。謝謝!!

+0

後來在感謝擡起頭來!我已更新該帖子;希望它現在更有意義 – 2015-04-05 18:16:06

回答

0

問題是,您不能映射到當前陣列的最終csv表,因爲價格比發票號更多。

您可以直接將數據寫入一個文件:

var sep = ";"; 
var fs = require('fs'); 
this.wait(2000, function() { 
    var invoiceNumber = this.fetchText('#InvoiceNumber'); 
    var invoiceDate = this.fetchText(x('//*[@id="printArea"]/table/tbody/tr[1]/td/table/tbody/tr/td[1]/table/tbody/tr[2]/td[2]')); 

    var description = this.evaluate(getDescriptions); 
    var price = this.evaluate(getPrices); 
    for(var i = 0; i < description.length; i++) { 
    // assume description and price have the same length 
    // append line: 
    fs.write("invoices.csv", invoiceNumber+sep+invoiceDate+sep+description[i]+sep+price[i]+"\n", "a"); 
    } 
}); 

或保存一切到一個數組迭代它

var invoices = []; 
this.wait(2000, function() { 
    var invoice = {}; 
    invoice.number = this.fetchText('#InvoiceNumber'); 
    invoice.date = this.fetchText(x('//*[@id="printArea"]/table/tbody/tr[1]/td/table/tbody/tr/td[1]/table/tbody/tr[2]/td[2]')); 

    invoice.descriptions = this.evaluate(getDescriptions); 
    invoice.prices = this.evaluate(getPrices); 
    invoices.push(invoice); 
}); 
+0

如果描述包含換行符或類似的東西,你可能需要調整它。 – 2015-04-05 20:27:42