2016-11-18 58 views
1

我需要从我在Delphi XE10(VCL)的TWebBrowser组件中显示的网站中删除一个小图像。我花了几个小时的搜索,我尝试了很多代码,但它不能按我的需要工作。从TWebBrowser中的活动html中删除特定的IMG标记

这是我的代码片段:

procedure TForm16.WebBrowser1DocumentComplete(ASender: TObject; 
    const pDisp: IDispatch; const [Ref] URL: OleVariant); 
var 
    Doc: IHTMLDocument2; 
    ElementCollection: IHTMLElementCollection; 
    Frames: IHTMLElementCollection; 
    Element: IHTMLElement; 
    Frame: IHTMLDOMNode; 
    i: Integer; 
begin 
    Doc := WebBrowser1.Document as IHTMLDocument2; 
    ElementCollection := Doc.body.all as IHTMLElementCollection; 
    Frames := ElementCollection.tags('IMG') as IHTMLElementCollection; 
    if Frames <> nil then 
    begin 
    for i := 0 to Frames.length - 1 do 
    begin 
     Element := Frames.item(i, 0) as IHTMLElement; 
     Frame := Element as IHTMLDOMNode; 
     if Frame <> nil then 
     begin 
     Frame.parentNode.removeChild(Frame); 
     end; 
    end; 
    end; 

end; 

不幸的是它会删除所有图像。我想删除具有特定HREF的特定图片。你能帮助我吗?

+0

你将它们全部遍历并全部删除。为什么要这样做,如果你只想删除其中的一个。 –

+0

感谢您的回复。 –

+0

我不想循环它们,以便我可以删除具有href ='exp.com/exp.png'的img节点,但我不知道如何实现它 –

回答

1

我不确定您是否在srchref属性之后。
我假设你实际上是指src(我不知道href使用IMG标签)。如果不是,请在下面的答案中将src替换为href

基本上你的代码很好。您可以检查IHTMLElement属性,例如

if Element.getAttribute('src', 0) = 'something' then ... 

我建议使用IHTMLDocument2.images收集直接和IHTMLImgElement它具有src/href性能,如:

procedure TForm1.WebBrowser1DocumentComplete(Sender: TObject; 
    const pDisp: IDispatch; var URL: OleVariant); 
var 
    Doc: IHTMLDocument2; 
    Images: IHTMLElementCollection; 
    Img: IHTMLImgElement; 
    Node: IHTMLDOMNode; 
    Src: WideString; 
    I: Integer; 
begin 
    Doc := TWebBrowser(Sender).Document as IHTMLDocument2; 
    if Assigned(Doc) then 
    begin 
    Images := Doc.images; 
    for I := Images.length - 1 downto 0 do 
    begin 
     Img := Images.item(I, 0) as IHTMLImgElement; 
     if Img.src = 'http://foo.bar/my.png' then // or "Img.href" 
     begin 
     Node := Img as IHTMLDOMNode; 
     Node.parentNode.removeChild(Node); 
     Break; // optional 
     end; 
    end; 
    end; 
end; 

请注意,我遍历DOM向后

for I := Images.length - 1 downto 0 do 

,因为如果我们需要删除多个节点,删除前一个节点后,我们不会放弃下一个节点索引。