Using TestPlan I produced a rough script. Given the complexity of web tables it'll likely need to be tailored on all sites.
This first script lists the tables on the page:
# A simple table scraping example. It lists the tables on a page
#
# Cmds.Site = the URL to scan
default %Cmds.Site% http://en.wikipedia.org/wiki/List_of_Olympic_records_in_athletics
GotoURL %Cmds.Site%
set %Count% 1
foreach %Table% in (response //table)
Notice Table #%Count%
# find a suitable name, look back for a header
set %Check% ./preceding::*[name()='h1' or name()='h2' or name()='h3'][1]
if checkIn %Table% %Check%
Notice (selectIn %Table% %Check%)
end
set %Count% as binOp %Count% + 1
end
The second script then extracts the data of one table into a CSV file.
# Generic extract of contents of a table in a webpage
# Use list_tables to get the list of table and indexes
#
# Cmds.Site = the URL to scan
# Cmds.Index = Table index to scan
default %Cmds.Site% http://en.wikipedia.org/wiki/List_of_Olympic_records_in_athletics
default %Cmds.Index% 2
GotoURL %Cmds.Site%
set %Headers% //table[%Cmds.Index%]/tbody/tr[1]
set %Rows% //table[%Cmds.Index%]/tbody/tr[position()>1]
# Get an cleanup the header fields
set %Fields% withvector
end
foreach %Header% in (response %Headers%/*)
putin %Fields% (trim %Header%)
end
Notice %Fields%
# Create an output CSV
call unit.file.CreateDataFile with
%Name% %This:Dir%/extract_table.csv
%Format% csv
%Fields% %Fields%
end
set %DataFile% %Return:Value%
# Now extract each row
foreach %Row% in (response %Rows%)
set %Record% withvector
end
foreach %Cell% in (selectIn %Row% ./td)
putin %Record% (trim %Cell%)
end
call unit.file.WriteDataFile with
%DataFile% %DataFile%
%Record% %Record%
end
end
call unit.file.CloseDataFile with
%DataFile% %DataFile%
end
My CSV file looks like below. Note that wikipedia has extract information in each cell. There are many ways to get rid of it, but not in a generic fashion.
Shot put,22.47 m,"Timmermann, UlfUlf Timmermann",East Germany (GDR),1988 1988 Seoul,"01988-09-23 September 23, 1988",[25]
Discus throw,69.89 m,"Alekna, VirgilijusVirgilijus Alekna",Lithuania (LTU),2004 2004 Athens,"02004-08-23 August 23, 2004",[26]
Hammer throw,84.80 m,"Litvinov, SergeySergey Litvinov",Soviet Union (URS),1988 1988 Seoul,"01988-09-26 September 26, 1988",[27]
Javelin throw,90.57 m,"Thorkildsen, AndreasAndreas Thorkildsen",Norway (NOR),2008 2008 Beijing,"02008-08-23 August 23, 2008",[28]
jq
andpup
installed (both useful tools in their own right), then see this answer for a one-liner that will very likely what you're looking for. If you want that exact syntax, wrap in some shell script that passes the first argument to an:nth-of-type()
CSS selector. – Haas