如何访问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;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值