上一篇:Delphi通过URL获取网页源码
下一篇:Delphi捕获TWebBrowser的Close事件

TWebBrowser访问网页中的表格(转载)

发布于: 2012-12-16 18:37:46   |  发布在: Delphi文章   |  点击:

Delphi利用TWebBrowser控件访问网页中的表格的方法:

use MSHTML;

function GetHtmlTableCell(aTable: IHTMLTable; aRow, aCol: Integer): IHTMLElement;
var
  Row: IHTMLTableRow;

begin
  Result := nil;
  if aTable = nil then Exit;
  if aTable.rows = nil then Exit;
  Row := aTable.rows.item(aRow, aRow) as IHTMLTableRow;
  if Row = nil then Exit;
  Result := Row.cells.item(aCol, aCol) as IHTMLElement;
end;

function GetHtmlTable(aDoc: IHTMLDocument2; aIndex: Integer): IHTMLTable;
var
  list: IHTMLElementCollection;
begin
  Result := nil;
  if aDoc = nil then Exit;
  if aDoc.all = nil then Exit;
  list := aDoc.all.tags('table') as IHTMLElementCollection;
  if list = nil then Exit;
  Result := list.item(aIndex,aIndex) as IHTMLTable;
end;

function GetWebBrowserHtmlTableCellText(const AWebBrowser: TWebBrowser;
  const TableIndex, RowIndex, ColIndex: Integer;
  var ResValue: string): Boolean;
var
  Docintf: IHTMLDocument2;
  tblintf: IHTMLTable;
  node: IHTMLElement;
begin
  ResValue := '';
  docintf := AWebBrowser.Document as IHTMLDocument2;
  tblintf := GetHtmlTable(docintf, TableIndex);
  node := GetHtmlTableCell(tblintf, RowIndex, ColIndex);
  Result := node <> nil;
  if Result then
    ResValue := Trim(node.innerText);
end;

function GetHtmlTableRowHtml(aTable: IHTMLTable; aRow: Integer): IHTMLElement;
var
  Row: IHTMLTableRow;
begin
  Result := nil;
  if aTable = nil then Exit;
  if aTable.rows = nil then Exit;
  Row := aTable.rows.item(aRow, aRow) as IHTMLTableRow;
  if Row = nil then Exit;
  Result := Row as IHTMLElement;
end;

function GetWebBrowserHtmlTableCellHtml(const AWebBrowser: TWebBrowser;
  const TableIndex, RowIndex, ColIndex: Integer;
  var ResValue: string): Boolean;
var
  Docintf: IHTMLDocument2;
  tblintf: IHTMLTable;
  node: IHTMLElement;
begin
  ResValue := '';
  docintf := AWebBrowser.Document as IHTMLDocument2;
  tblintf := GetHtmlTable(docintf, TableIndex);
  node := GetHtmlTableCell(tblintf, RowIndex, ColIndex);
  Result := node <> nil;
  if Result then
    ResValue := Trim(node.innerHTML);
end;

function GeHtmlTableHtml(aTable: IHTMLTable; aRow: Integer): IHTMLElement;
var
  Row: IHTMLTableRow;
begin
  Result := nil;
  if aTable = nil then Exit;
  if aTable.rows = nil then Exit;
  Row := aTable.rows.item(aRow, aRow) as IHTMLTableRow;
  if Row = nil then Exit;
  Result := Row as IHTMLElement;
end;

function GetWebBrowserHtmlTableHtml(const AWebBrowser: TWebBrowser;
  const TableIndex, RowIndex: Integer;
  var ResValue: string): Boolean;
var
  Docintf: IHTMLDocument2;
  tblintf: IHTMLTable;
  node: IHTMLElement;
begin
  ResValue := '';
  docintf := AWebBrowser.Document as IHTMLDocument2;
  tblintf := GetHtmlTable(docintf, TableIndex);
  node := GeHtmlTableHtml(tblintf, RowIndex);
  Result := node <> nil;
  if Result then
    ResValue := node.innerHtml;
end;

TWebBrowser网页