如何将HTML表格(<table>
)的内容转换为CSV格式?是否有库或Linux程序可以实现此功能?这类似于在Internet Explorer中复制表格,并将其粘贴到Excel中。
如何将HTML表格(<table>
)的内容转换为CSV格式?是否有库或Linux程序可以实现此功能?这类似于在Internet Explorer中复制表格,并将其粘贴到Excel中。
这种方法并不是一个真正的库或程序,但用于临时转换时,您可以:
我知道这适用于Excel,而我相信我已经在OpenOffice电子表格上这样做过。
但您可能更喜欢Perl或Ruby脚本......
抱歉打扰了这个古老的主题,但我最近想要做到这一点,但我想要一个完全可移植的bash脚本来完成它。因此,这里是我的解决方案,只使用grep和sed。
以下内容很快就被敲出来了,因此可以更加优雅,但我只是刚刚开始使用sed/awk等工具...
curl "http://www.webpagewithtableinit.com/" 2>/dev/null | grep -i -e '</\?TABLE\|</\?TD\|</\?TR\|</\?TH' | sed 's/^[\ \t]*//g' | tr -d '\n' | sed 's/<\/TR[^>]*>/\n/Ig' | sed 's/<\/\?\(TABLE\|TR\)[^>]*>//Ig' | sed 's/^<T[DH][^>]*>\|<\/\?T[DH][^>]*>$//Ig' | sed 's/<\/T[DH][^>]*><T[DH][^>]*>/,/Ig'
您可以看到,我使用curl获取了页面源代码,但您也可以轻松地从其他地方获取表格源代码。
以下是解释:
使用cURL获取URL的内容,将stderr转储为null(没有进度条)。
curl "http://www.webpagewithtableinit.com/" 2>/dev/null
我只想要表格元素(仅返回带有TABLE、TR、TH、TD标签的行)
| grep -i -e '</\?TABLE\|</\?TD\|</\?TR\|</\?TH'
移除行首的任何空格。
| sed 's/^[\ \t]*//g'
去除换行符
| tr -d '\n\r'
将</TR>
替换为换行符
| sed 's/<\/TR[^>]*>/\n/Ig'
删除表格和行标签
| sed 's/<\/\?\(TABLE\|TR\)[^>]*>//Ig'
移除 ^<TD>
,^<TH>
,</TD>$
,</TH>$
| sed 's/^<T[DH][^>]*>\|<\/\?T[DH][^>]*>$//Ig'
将</TD><TD>
替换为逗号
| sed 's/<\/T[DH][^>]*><T[DH][^>]*>/,/Ig'
请注意,如果表格单元格中包含逗号,则可能需要先对其进行转义或使用其他分隔符。
希望这能对某人有所帮助!
<td>\ncell value\n</td>
),而这个脚本最终会剥离掉那些数据,因为它会删除每一行中没有表格标签的内容。 - Hayden Schiff这是一个使用nokogiri的Ruby脚本-- http://nokogiri.rubyforge.org/nokogiri/
require 'nokogiri'
doc = Nokogiri::HTML(table_string)
doc.xpath('//table//tr').each do |row|
row.xpath('td').each do |cell|
print '"', cell.text.gsub("\n", ' ').gsub('"', '\"').gsub(/(\s){2,}/m, '\1'), "\", "
end
print "\n"
end
对于我的基本测试用例有效。
补充这些答案(因为我最近也在尝试类似的事情) - 如果谷歌电子表格是您选择的电子表格程序,只需执行以下两个步骤。
1. 删除围绕表格开/闭标签的html文件中的所有内容,并将其另存为另一个html文件。
2. 直接将该html文件导入到谷歌电子表格中,您将美观地导入信息(顶级提示:如果在表格中使用了内联样式,它们也会被导入!)
这为我节省了大量时间,并避免了不同格式之间的繁琐转换。
这是我写的一个短小的Python程序,用来完成这个任务。它只花了几分钟时间编写,所以可能还可以改进。不确定它如何处理嵌套表格(可能会做一些不好的事情)或多个表格(可能它们只会一个接一个地出现)。它不处理 colspan
或 rowspan
。
from HTMLParser import HTMLParser
import sys
import re
class HTMLTableParser(HTMLParser):
def __init__(self, row_delim="\n", cell_delim="\t"):
HTMLParser.__init__(self)
self.despace_re = re.compile(r'\s+')
self.data_interrupt = False
self.first_row = True
self.first_cell = True
self.in_cell = False
self.row_delim = row_delim
self.cell_delim = cell_delim
def handle_starttag(self, tag, attrs):
self.data_interrupt = True
if tag == "table":
self.first_row = True
self.first_cell = True
elif tag == "tr":
if not self.first_row:
sys.stdout.write(self.row_delim)
self.first_row = False
self.first_cell = True
self.data_interrupt = False
elif tag == "td" or tag == "th":
if not self.first_cell:
sys.stdout.write(self.cell_delim)
self.first_cell = False
self.data_interrupt = False
self.in_cell = True
def handle_endtag(self, tag):
self.data_interrupt = True
if tag == "td" or tag == "th":
self.in_cell = False
def handle_data(self, data):
if self.in_cell:
#if self.data_interrupt:
# sys.stdout.write(" ")
sys.stdout.write(self.despace_re.sub(' ', data).strip())
self.data_interrupt = False
parser = HTMLTableParser()
parser.feed(sys.stdin.read())
table
的HTML页面,我建议使用以下解决方案。对我来说非常有效:table
的HTML页面,我建议使用以下解决方案。对我来说非常有效:$(document).ready(() => {
$("#buttonExport").click(e => {
// Getting values of current time for generating the file name
const dateTime = new Date();
const day = dateTime.getDate();
const month = dateTime.getMonth() + 1;
const year = dateTime.getFullYear();
const hour = dateTime.getHours();
const minute = dateTime.getMinutes();
const postfix = `${day}.${month}.${year}_${hour}.${minute}`;
// Creating a temporary HTML link element (they support setting file names)
const downloadElement = document.createElement('a');
// Getting data from our `div` that contains the HTML table
const dataType = 'data:application/vnd.ms-excel';
const tableDiv = document.getElementById('divData');
const tableHTML = tableDiv.outerHTML.replace(/ /g, '%20');
// Setting the download source
downloadElement.href = `${dataType},${tableHTML}`;
// Setting the file name
downloadElement.download = `exported_table_${postfix}.xls`;
// Trigger the download
downloadElement.click();
// Just in case, prevent default behaviour
e.preventDefault();
});
});
来源: http://www.kubilayerdogan.net/?p=218
你可以在这里编辑文件格式为.csv
:
downloadElement.download = `exported_table_${postfix}.csv`;
以下是不使用任何外部库的简单解决方案:
https://www.codexworld.com/export-html-table-data-to-csv-using-javascript/
我已经试用此方法,没有遇到任何问题。
基于audiodude的回答,但是通过使用内置的CSV库来简化
require 'nokogiri'
require 'csv'
doc = Nokogiri::HTML(table_string)
csv = CSV.open("output.csv", 'w')
doc.xpath('//table//tr').each do |row|
tarray = [] #temporary array
row.xpath('td').each do |cell|
tarray << cell.text #Build array of that row of data.
end
csv << tarray #Write that row out to csv file
end
csv.close
我曾想知道是否有办法将Nokogiri NodeSet(row.xpath('td')
)作为数组一次性写入csv文件。但我只能想到通过迭代每个单元格并构建临时数组来完成每个单元格内容的操作。