使用TestPlan 我制作了一个粗略的脚本。鉴于网络表格的复杂性,它可能需要针对所有网站进行定制。
第一个脚本列出了页面上的表格:
# 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
然后第二个脚本将一个表的数据提取到一个 CSV 文件中。
# 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
我的 CSV 文件如下所示。请注意,维基百科在每个单元格中都有提取信息。有很多方法可以摆脱它,但不是通用的。
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]