Delphi TWebBrowser[6] 获取网页所有链接(元素)、下拉菜单及GetElementByID返回值的有效性判定方法

Delphi TWebBrowser[6] 获取网页所有链接(元素)、下拉菜单及GetElementByID返回值的有效性判定方法

1、获取网页所有链接

var
  elem: IHTMLElement;
  coll: IHTMLElementCollection;
  i: integer;
  url, title: string;
begin
  coll := (WebBrowser1.Document as IHTMLDocument2).all;
  coll := (coll.tags('a') as IHTMLElementCollection);
  for i := 0 to coll.Length - 1 do
  begin //   循环取出每个链接
    elem := (coll.item(i, 0) as IHTMLElement);
    url := Trim(string(elem.getAttribute(WideString('href'), 0)));
    title := elem.innerText;
    ShowMessage(Format('链接标题:%s,链接网址:%s', [title, url]));
  end;
end;

其他元素的获取,方法类似

2、下拉菜单

uses MsHtml;

var
  doc: IHTMLDocument2;
  coll: IHTMLElementCollection;
  iPos, iIndex: Integer;
  selElem: IHtmlSelectElement;
  optElem: IHtmlOptionElement;
begin
  doc := WebBrowser1.Document as IHTMLDocument2;
  if doc = nil then Exit;

  coll := doc.all.tags('select') as IHTMLElementCollection;
  iPos := 0; //要访问的下拉菜单的序号,从0开始为第一个
  selElem := coll.item(iPos, 0) as IHtmlSelectElement;
  if selElem = nil then Exit;

  iIndex := 2; //下拉菜单的选项序号,从0开始为第一个,2为第三个选项
  optElem := selElem.item(iIndex, 0) as IHtmlOptionElement;
  if optElem = nil then Exit;

  ShowMessage(optElem.text); //获取该选项的值
  optElem.selected := True;  //选中该选项
end;  

3、 GetElementByID返回值有效性判定方法

var
  aElement: OleVariant;
begin
  aElement := WebBrowser1.OleObject.Document.GetElementByID('btnLogin');
  if IDispatch(aElement) <> nil then //对返回值进行有效性检查
  begin
    aElement.value := '登录按钮';
    aElement.click;
  end;
end;

  

创建时间:2020.11.23  更新时间:  

博客园 滔Roy https://www.cnblogs.com/guorongtao 希望内容对你所有帮助,谢谢!
原文地址:https://www.cnblogs.com/guorongtao/p/14022777.html