【问题标题】:Scraping images from Website in delphi with twebbrowser使用 twebbrowser 从 Delphi 中的网站抓取图像
【发布时间】:2016-05-23 19:52:36
【问题描述】:

我正在尝试制作一个小工具,可以从访问的站点下载所有图像。它必须使用 twebbrowser 组件制作。我客户的测试站点是Click。目前我用 getelementbyid 选择图片,但有些图片没有 id。我该如何解决失踪的问题?非常感谢

【问题讨论】:

  • 通过 dom 寻找图像

标签: image delphi twebbrowser


【解决方案1】:

页面加载完成后,查询TWebBrowser.Document属性为IHTMLDocument2接口,然后就可以枚举IHTMLDocument2.images集合的元素了:

var
  Document: IHTMLDocument2;
  Images: IHTMLElementCollection;
  Image: IHTMLImgElement;
  I: Integer;
begin
  Document := WebBrowser1.Document as IHTMLDocument2;
  Images := Document.images;
  For I := 0 to Images.length - 1 do
  begin
    Image := Images.item(I, '') as IHTMLImgElement;
    // use Image as needed...
  end;
end;

请注意,这只会在 HTML <img> 标记中找到图像。如果您还需要在<input type="image"> 标签中查找图像,则必须枚举IHTMLDocument2.all 集合的元素以查找IHTMLInputElement 接口的实例,其type 属性为"image",例如:

var
  Document: IHTMLDocument2;
  Elements: IHTMLElementCollection;
  Element: IHTMLElement;
  Image: IHTMLImgElement;
  Input: IHTMLInputElement;
  I: Integer;
begin
  Document := WebBrowser1.Document as IHTMLDocument2;
  Elements := Document.all;
  For I := 0 to Elements.length - 1 do
  begin
    Element := Elements.item(I, '') as IHTMLElement;
    if Element is IHTMLImgElement then begin
      Image := Element as IHTMLImgElement;
      // use Image as needed...
    end
    else if Element is IHTMLInputElement then begin
      Input := Element as IHTMLInputElement;
      if Input.type = 'image' then
      begin
        // use Input as needed...
      end;
    end;
  end;
end;

【讨论】:

    【解决方案2】:

    您可以“遍历”文档并使用 WebDocument.all.item(itemnum,'') 查看每个元素,而不是通过 id 请求特定元素。

    var
      cAllElements: IHTMLElementCollection;
      eThisElement: IHTMLElement;
      WebDocument: IHTMLDocument2;
    

    =======

     cAllElements:=WebDocument.All
      For iThisElement:=0 to cAllElements.num-1 do
        begin
          eThisElement:=cAllElements.item(iThisElement,'') as IHTMLElement;
          // check out eThisElement and do what you want
        end;
    

    然后,您将查看 IMG 的元素 .tagName,或进行任何您需要的评估以确定它是否是图片并像以前一样处理它。

    【讨论】:

    • 遍历文档的images 集合比遍历all 集合更直接。
    • 我同意。我忘记了图像集。两者都可以,但使用图像集合会更直接。 .all 集合对于临时搜索更有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2020-08-05
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    相关资源
    最近更新 更多