簡體   English   中英

Delphi webbrowser - 如何從id中的標記名獲取值

[英]Delphi webbrowser - How to Get value from tag name inside id

我正在使用delphi 7並制作小程序,其中我使用webbrowser從id中的標簽獲取值

這是保存值的html示例

<div id="download" style="display: block;">

    <a style="display:none" href="blablabla"></a>
    <a href="Need This value"></a>
    <a style="display:none"blablabla"></a>
    <a style="display:none"blablabla"></a>
    <span style="margin-left:8px; color:#808080; overflow:hidden; white-space: nowrap"></span>
</div>

我可以獲得id“下載”的innerHTML我的問題是如何從標簽“a”獲得“href”的值

如果有問題的<a>標簽分配了nameid ,您可以簡單地使用IHTMLDocument2.anchors集合來查找它,例如:

var
  Doc: IHTMLDocument2;
  Anchor: IHTMLAnchorElement;
  Value: String;
begin
  Doc := WebBrowser1.Document as IHTMLDocument2;
  Anchor := Doc.anchors.item('name', 0) as IHTMLAnchorElement;
  Value := Anchor.href;
end;

但是,由於它沒有nameid ,因此您需要進一步深入挖掘DOM,例如:

var
  Doc: IHTMLDocument3;
  Download: IHTMLElement;
  Coll: IHTMLElementCollection;
  Anchor: IHTMLAnchorElement;
  Value: String;
begin
  Doc := WebBrowser1.Document as IHTMLDocument3;
  Download := Doc.getElementById('download') as IHTMLElement;
  Coll := Download.children as IHTMLElementCollection;
  Coll := Coll.tags('a') as IHTMLElementCollection;
  Anchor := Coll.item(1, 0) as IHTMLAnchorElement;
  Value := Anchor.href;
end;

不知道它是否是最好的解決方案,但它在這里工作:

function FindYourValue(block : string) : string;
var text, subtext : string;
    quant : integer;
begin
  text := block;
  if pos('<a href="',text) > 0 then
    subtext := copy(text,pos('<a href="',text) + 9,length(text));
  quant := pos('"',subtext);
  result := copy(subtext,1,9);
end;

其中BLOCK是從<div id="download" style="display: block;">例程獲得的字符串。

Remy Lebeau @RemyLebeau提供的解決方案應該可行。 但是,如果HTML不包含您期望的元素,則可能會遇到異常。 如果您想以更安全的方式編寫代碼,我建議您使用Supports來查詢Html元素接口。

function ExtractUrlExample: TStringList; 
var
  Doc: IHTMLDocument3;
  Download: IHTMLElement;
  Coll: IHTMLElementCollection;
  I: Integer;
  Anchor: IHTMLAnchorElement;
begin
  Result := TStringList.Create;
  if Supports(WebBrowser1.Document, IHTMLDocument3, Doc) and
     Supports(Doc.getElementById('download'), IHTMLElement, Download) and
     Supports(Download.children, IHTMLElementCollection, Coll) and
     Supports(Coll.tags('a'), IHTMLElementCollection, Coll) then
  begin
    for I := 0 to Coll.Length - 1 do
      if Supports(Coll.item(I, 0), IHTMLAnchorElement, Anchor) then
        Result.Add(Anchor.href); // The Url you want to extract
  end;
end;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM