温馨提示×

Delphi如何获取html表格中的数据

小亿
86
2024-03-21 17:02:54
栏目: 编程语言

要获取HTML表格中的数据,可以使用Delphi中的TWebBrowser组件来加载HTML页面,并通过解析HTML文档来提取表格中的数据。以下是一个简单的示例代码,演示如何获取HTML表格中的数据:

uses
  MSHTML;

procedure TForm1.btnGetTableDataClick(Sender: TObject);
var
  HTMLDocument: IHTMLDocument2;
  Table: IHTMLTable;
  Row: IHTMLTableRow;
  Cell: IHTMLTableCell;
  i, j: Integer;
begin
  if Assigned(WebBrowser1.Document) then
  begin
    HTMLDocument := WebBrowser1.Document as IHTMLDocument2;
    if Assigned(HTMLDocument) then
    begin
      Table := HTMLDocument.all.tags('table').item(0, 0) as IHTMLTable;
      if Assigned(Table) then
      begin
        for i := 0 to Table.rows.length - 1 do
        begin
          Row := Table.rows.item(i, 0) as IHTMLTableRow;
          for j := 0 to Row.cells.length - 1 do
          begin
            Cell := Row.cells.item(j, 0) as IHTMLTableCell;
            ShowMessage(Cell.innerText);
          end;
        end;
      end;
    end;
  end;
end;

上述代码首先获取WebBrowser组件加载的HTML文档,然后遍历表格中的每一行和每一列,通过innerText属性获取单元格中的文本内容,并使用ShowMessage方法显示出来。您可以根据需要对获取到的数据进行进一步处理或存储。

0