|
|
| |
|
Delphi如何访问WebBrowser里的各种元素 | |
| 阅读 223 次 更新时间:2022/7/5 | |
Delphi如何访问WebBrowser里的各种元素
一、访问网页中指定类型的元素 比如网页有一段“<div class="c-font ">其他人还在搜</div>”,如果我要访问类型名称是“c-font”的元素,我会想到访问它的Class属性。 引用MSHTML 代码如下 Var doc: IHtmlDocument2; i:integer; begin doc:=webbrowser1.Document as IHtmlDocument2; for i:= 0 to doc.all.length-1 do begin if (doc.all.item(i,EmptyParam) as IHTMLElement).getAttribute('class',0)=’c-font’ then begin //代码 End; End; end; 但运行的时候你会发现出错,没有Class这个属性,这是为什么?其实Class是个关键字,如果想访问类型名称应该用”classname”。 if (doc.all.item(i,EmptyParam) as IHTMLElement).getAttribute('classname',0)=’c-font’ then begin //代码 End; 这样写就能正常访问做类型名称了。 二、如何保证不出错 在访问WebBrowser里的元素时容易出现各种错误,所以我在访问IHTMLElement的属性时写了一个统一的函数,这样语言就会简洁很多。 Function GetItemArrtribute(HItem: IHTMLElement; ItemName: string): OleVariant; begin VarClear(Result); //初始化返回结果为空值 try if HItem=nil then //有可能要访问的IHTMLElement不存在 Exit; if VarType(HItem.getAttribute(ItemName,0))= varEmpty then //有可能属性不存在 Exit; Result:=HItem.getAttribute(ItemName,0); except on E: Exception do VarClear(Result); end; end; 调用过程 Var doc: IHtmlDocument2; tmp,sTitle:string; i:integer; begin doc:=webbrowser1.Document as IHtmlDocument2; for i:= 0 to doc.all.length-1 do //遍历网页所有元素 begin tmp:=GetItemArrtribute((doc.all.item(i,EmptyParam) as IHTMLElement),'className'); if tmp='imgitem' then //找到指定类型名称的元素 begin sTitle:=GetItemArrtribute((doc.all.item(i,EmptyParam) as IHTMLElement),'data-objurl'); //访问元素的data-objurl属性 End; end; end; | |
|
|
|