从shell将HTML表格转换为CSV文件

时间:2014-02-25 15:01:30

标签: linux bash csv libreoffice

我试图将带有HTML表格的文件转换为CSV格式。该文件的摘录如下:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="Head1"><link rel="shortcut icon" href="favicon.ico" /><title>
Untitled Page
    </title></head>
    <body>
        <form name="form1" method="post" action="mypricelist.aspx" id="form1">
    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/somethingrandom" />

<div>
    <table id="price_list" border="0">
<tr>
    <td>ProdCode</td><td>Description</td><td>Your Price</td>
</tr><tr>
    <td>ab101</td><td>loruem</td><td>1.1</td>
</tr><tr>
    <td>ab102</td><td>ipsum</td><td>0.1</td>
</tr><tr>

我尝试使用

    xls2csv -x -c\; evprice.xls > evprice.csv

但这给我一个错误说

    evprice.xls is not OLE file or Error
我用Google搜索了一下。它说那是因为文件不合适xls而只是html。

当我尝试

    file evprice.xls

它说它的html因此找到了一个“解决方案”,使用libreoffice。

    libreoffice --headless -convert-to csv ./evprice.xls 

这不会给出错误,但csv输出文件很奇怪,就像在记事本中打开exe文件一样。

它包含很多像这些奇怪的字符

    —¬ž­þ9ü~ÆóXþK¢

任何人都知道为什么会这样,并找到了有效的解决方案?

1 个答案:

答案 0 :(得分:1)

我已经构建了一个Python实用程序,它将HTML文件中的所有表转换为单独的CSV文件。

你可以找到它here

剧本的关键在于:

from BeautifulSoup import BeautifulSoup
import csv

filename = "MY_HTML_FILE"
fin      = open(filename,'r')

print "Opening file"
fin  = fin.read()

print "Parsing file"
soup = BeautifulSoup(fin,convertEntities=BeautifulSoup.HTML_ENTITIES)

print "Preemptively removing unnecessary tags"
[s.extract() for s in soup('script')]

print "CSVing file"
tablecount = -1
for table in soup.findAll("table"):
  tablecount += 1
  print "Processing Table #%d" % (tablecount)
  with open(sys.argv[1]+str(tablecount)+'.csv', 'wb') as csvfile:
    fout = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    for row in table.findAll('tr'):
      cols = row.findAll(['td','th'])
      if cols:
        cols = [x.text for x in cols]
        fout.writerow(cols)