http://jsfiddle.net/GMmdg/5/
一般选择器格式:
xtract('table.container-of-inner-tables table.child-tables');
jsfiddle 的具体选择器,但它可能不适用于实际页面:
xtract('body > table > tbody > tr:not(.qprintfoot) table');
数据提取器功能,必要时更改内部选择器:
function xtract( rootTableSelector ){
var rows = [];
var csv = [];
$( rootTableSelector ).each(function(){
var $t = $(this);
var row = {};
row.name = $.trim( $t.find('tr:nth-child(1) > td > b').text());
row.email = $.trim( $t.find('tr:nth-child(2) > td > div:nth-child(2)').text());
rows.push( row );
csv.push([ row.name, row.email ]);
});
console.log( rows );
$('#result').text( toCSV( csv ) );
$('#json').text( JSON.stringify( rows) );
// prompt('this is not csv', csv );
}
未经测试,新编写的创建 csv 的函数,享受以下选项:
function toCSV( rows ){
var newline = '\n';
var fsep = ','; // field separator
var quot = '"'; // field quoter
var quotquot = [ quot + quot, '\\' + quot ][1]; // choose
var alwaysQuote = false;
var quoteIfContainsQuote = true;
// omitted option possibilities:
// - trimFields
// - quoteStringsButNotNumbers(excel)
// - putEqualSignBeforeNumbers(excel), etc.
var lines = [];
$.each( rows, function(){
var line = [];
$.each( this, function(){
var s = this;
var needsQuote = alwaysQuote;
if( s.indexOf( fsep ) >= 0 )
needsQuote = true;
if( s.indexOf( quot ) >= 0 ){
needsQuote = needsQuote || quoteIfContainsQuote;
s = s.replace( quot, quotquot );
}
if( needsQuote ) s = quot + s + quot;
line.push( s );
});
lines.push( line.join( fsep ));
});
return lines.join( newline );
}
http://pastebin.com/vCuVBUvE
javascript:(function()%7Bfunction%20e(e)%7Bvar%20t%3D%22%5Cn%22%2Cn%3D%22%2C%22%2Cr%3D'%22'%2Ci%3D%5Br%2Br%2C%22%5C%5C%22%2Br%5D%5B1%5D%2Cs%3D!1%2Co%3D!0%2Cu%3D%5B%5D%3Breturn%20%24.each(e%2Cfunction()%7Bvar%20e%3D%5B%5D%3B%24.each(this%2Cfunction()%7Bvar%20t%3Dthis%2Cu%3Ds%3Bt.indexOf(n)%3E%3D0%26%26(u%3D!0)%2Ct.indexOf(r)%3E%3D0%26%26(u%3Du%7C%7Co%2Ct%3Dt.replace(r%2Ci))%2Cu%26%26(t%3Dr%2Bt%2Br)%2Ce.push(t)%7D)%2Cu.push(e.join(n))%7D)%2Cu.join(t)%7Dfunction%20t(t)%7Bvar%20n%3D%5B%5D%2Cr%3D%5B%5D%3B%24(t).each(function()%7Bconsole.log(this)%3Bvar%20e%3D%24(this)%2Ct%3D%7B%7D%3Bt.name%3D%24.trim(e.find(%22tr%3Anth-child(1)%20%3E%20td%20%3E%20b%22).text())%2Ct.email%3D%24.trim(e.find(%22tr%3Anth-child(2)%20%3E%20td%20%3E%20div%3Anth-child(2)%22).text())%2Cn.push(t)%2Cr.push(%5Bt.name%2Ct.email%5D)%7D)%2Cr%3De(r)%2Cconsole.log(n)%2C%24(%22body%22).prepend('%3Cpre%20id%3D%22result%22%3E%3C%2Fpre%3E')%2C%24(%22img%2C.qprintable%22).remove()%2C%24(%22%23result%22).text(r)%2C%24(%22%23json%22).text(JSON.stringify(n))%2Cprompt(%22Select%20all%20and%20copy%22%2Cr)%7Dfunction%20r()%7Bvar%20e%3Dwindow.jQuery%3Bif(!e)%7BsetTimeout(r%2C100)%3Breturn%7De(function()%7Bt(%22.qprintable2%22)%7D)%7Dvar%20n%3Ddocument.createElement(%22script%22)%3Bn.setAttribute(%22src%22%2C%22http%3A%2F%2Fcode.jquery.com%2Fjquery.min.js%22)%2Cn.setAttribute(%22type%22%2C%22text%2Fjavascript%22)%2Cdocument.getElementsByTagName(%22body%22)%5B0%5D.appendChild(n)%2Cr()%7D)()