forked from r-barnes/html2csv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml2csv.py
More file actions
executable file
·67 lines (56 loc) · 2.28 KB
/
html2csv.py
File metadata and controls
executable file
·67 lines (56 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Richard's html2csv converter
#rbarnes@umn.edu
#
from bs4 import BeautifulSoup
import os
import sys
import csv
import argparse
parser = argparse.ArgumentParser(description='Reads in an HTML and attempts to convert all tables into CSV files.')
parser.add_argument('--delimiter', '-d', action='store', default=',',help="Character with which to separate CSV columns")
parser.add_argument('--quotechar', '-q', action='store', default='"',help="Character within which to nest CSV text")
parser.add_argument('--ignoreempty', '-e', action='store_true', help="Ignore empty tables. Helps reduce output on table-layout html pages.")
parser.add_argument('filename',nargs="?",help="HTML file from which to extract tables")
args = parser.parse_args()
if sys.stdin.isatty() and not args.filename:
parser.print_help()
sys.exit(-1)
elif not sys.stdin.isatty():
args.filename = sys.stdin
else:
args.filename = open(sys.argv[1],'r')
print("Opening file")
fin = args.filename.read()
print("Parsing file")
soup = BeautifulSoup(fin,"html.parser")
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
tableisempty = True
print("Processing Table #%d" % (tablecount))
outfilename = sys.argv[1]+str(tablecount)+'.csv'
with open(outfilename, 'w', newline='') as csvfile:
fout = csv.writer(csvfile, delimiter=args.delimiter, quotechar=args.quotechar, quoting=csv.QUOTE_MINIMAL)
rowcount = 1
#Removes nested tables. for handling the sins of 1990's web pages.
[t.extract() for t in table.findAll("table")]
#This would grab all TRs regardless of depth without the above line removing nested tables
for row in table.findAll('tr'):
print(f"Processing row number {rowcount}")
rowcount += 1
cols = row.findAll(['td','th'])
print(f"Found {len(cols)} columns.")
if cols:
cols = [str(x.text).strip() for x in cols]
if (len(cols) > 1) or len(cols[0]) > 0 :
tableisempty = False
if not tableisempty:
fout.writerow(cols)
if args.ignoreempty and tableisempty:
print(f"Removing {outfilename} because it is empty and `-e` flag was activated.")
os.remove(outfilename)