温馨提示×

Delphi怎么获取html表格中的数据

小亿
213
2023-12-01 19:17:20
栏目: 编程语言

可以使用Delphi的TWebBrowser组件来获取HTML表格中的数据。

首先,在Delphi的Form中放置一个TWebBrowser组件,并设置其Align属性为alClient,这样可以使其铺满整个Form。

然后,在代码中使用TWebBrowser的Navigate方法加载HTML文件或者URL,如:

procedure TForm1.FormCreate(Sender: TObject); begin WebBrowser1.Navigate('http://www.example.com/table.html'); end; 

接下来,在WebBrowser的DocumentCompleted事件中,可以使用TWebBrowser的Document属性来获取HTML文档对象,然后通过其接口来获取表格数据。

假设HTML中的表格有id属性为"myTable",可以使用以下代码获取表格数据:

procedure TForm1.WebBrowser1DocumentCompleted(Sender: TObject; const pDisp: IDispatch; const URL: OleVariant); var HTMLDoc: IHTMLDocument2; Table: IHTMLElement; Rows: IHTMLElementCollection; Row: IHTMLElement; Cell: IHTMLElement; i, j: Integer; begin HTMLDoc := WebBrowser1.Document as IHTMLDocument2; Table := HTMLDoc.getElementById('myTable') as IHTMLElement; Rows := Table.getElementsByTagName('tr') as IHTMLElementCollection; for i := 0 to Rows.length - 1 do begin Row := Rows.item(i, EmptyParam) as IHTMLElement; for j := 0 to Row.cells.length - 1 do begin Cell := Row.cells.item(j, EmptyParam) as IHTMLElement; ShowMessage(Cell.innerText); end; end; end; 

以上代码将会逐行逐列地遍历表格,使用ShowMessage函数显示每个单元格的内容。你可以根据自己的需求进行进一步的处理。

0