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

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

1、获取网页所有链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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、下拉菜单

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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返回值有效性判定方法

1
2
3
4
5
6
7
8
9
10
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  更新时间:  

posted on   滔Roy  阅读(447)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报

导航

点击右上角即可分享
微信分享提示