IdentifiantMot de passe
Loading...
Mot de passe oubli� ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les r�ponses en temps r�el, voter pour les messages, poser vos propres questions et recevoir la newsletter

Codes sources � t�l�charger Delphi Discussion :

TLinkExplorer � Explorateur de liens et m�dias web


Sujet :

Codes sources � t�l�charger Delphi

  1. #1
    Membre exp�riment�
    Avatar de XeGregory
    Homme Profil pro
    Passionn� par la programmation
    Inscrit en
    Janvier 2017
    Messages
    541
    D�tails du profil
    Informations personnelles :
    Sexe : Homme
    �ge : 36
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activit� : Passionn� par la programmation
    Secteur : High Tech - Mat�riel informatique

    Informations forums :
    Inscription : Janvier 2017
    Messages : 541
    Par d�faut TLinkExplorer � Explorateur de liens et m�dias web
    Classe pour explorer r�cursivement un site, extraire liens, images et documents, et afficher les r�sultats dans TListBox/TTreeView avec compteurs et arr�t contr�l�.

    Code : S�lectionner tout - Visualiser dans une fen�tre � part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    unit LinkExplorerCore;
     
    interface
     
    uses
      System.Net.HttpClient, System.Net.HttpClientComponent, System.SysUtils,
      System.Classes,
      RegularExpressions, Generics.Collections, Vcl.Forms, Vcl.StdCtrls,
      Vcl.ComCtrls;
     
    type
      // TLinkExplorer: classe principale pour explorer un site web,
      // détecter les liens, images et documents, et les afficher dans des
      // composants VCL (TListBox, TTreeView, TLabel).
      TLinkExplorer = class
      private
        // Dictionnaire de liens visités pour éviter les boucles et les doublons.
        VisitedLinks: TDictionary<string, Boolean>;
        // Compteur total de liens parcourus.
        TotalLinks: Integer;
        // Compteur total de fichiers (images + documents) ajoutés à l'arbre.
        FileCount: Integer;
        // Indicateur pour arrêter proprement l'exploration depuis l'UI.
        StopProcess: Boolean;
     
        // Récupère le contenu HTML d'une URL et le retourne comme string.
        function GetWebContent(const URL: string): string;
     
        // Extrait les URLs des balises <a href="..."> du HTML.
        // BaseURL est utilisé pour construire des URLs relatives.
        procedure ExtractLinks(const HTML: string; BaseURL: string;
          var LinkList: TStringList);
     
        // Extrait les sources médias (<img src=...> et liens de type pdf/html/css).
        // Remplit deux listes distinctes: ImageList et DocList.
        procedure ExtractMediaSources(const HTML: string; BaseURL: string;
          var ImageList, DocList: TStringList);
     
        // Ajoute les fichiers trouvés (images/documents) au TTreeView fourni.
        // Met aussi à jour le label indiquant le nombre total de fichiers.
        procedure AddFilesToTreeView(ImageList, DocList: TStringList;
          TreeView: TTreeView; FileLabel: TLabel);
     
        // Fonction récursive qui explore les liens jusqu'à une profondeur donnée.
        // Met à jour la ListBox (liste de pages parcourues), le TreeView (fichiers),
        // et les labels de compteurs.
        procedure ExploreLinksRecursive(const URL: string; ListBox: TListBox;
          TreeView: TTreeView; LabelCounter, FileLabel: TLabel; Depth: Integer);
      public
        // Démarre l'exploration depuis une URL, initialise les variables internes.
        // MaxDepth = profondeur maximale d'exploration (1 = seul la page initiale).
        procedure ExploreLinks(const URL: string; ListBox: TListBox;
          TreeView: TTreeView; LabelCounter, FileLabel: TLabel; MaxDepth: Integer);
     
        // Demande l'arrêt de l'exploration en cours (l'exploration vérifie StopProcess).
        procedure StopExploration;
      end;
     
    implementation
     
    uses
      System.IOUtils;
     
    procedure TLinkExplorer.StopExploration;
    begin
      // Indique au processus récursif qu'il doit s'arrêter dès que possible.
      StopProcess := True;
    end;
     
    function TLinkExplorer.GetWebContent(const URL: string): string;
    var
      Client: TNetHTTPClient;
      Response: TStringStream;
    begin
      // Initialise la valeur de retour vide par défaut.
      Result := '';
     
      // Création d'un client HTTP et d'un flux pour récupérer la réponse.
      Client := TNetHTTPClient.Create(nil);
      Response := TStringStream.Create;
      try
        try
          // Requête GET simple; le contenu renvoyé est placé dans Response.
          Client.Get(URL, Response);
          Result := Response.DataString;
        except
          // En cas d'erreur réseau ou autre, affiche un message dans la console.
          on E: Exception do
            Writeln('Erreur : ' + E.Message);
        end;
      finally
        // Libération des objets pour éviter les fuites mémoire.
        Client.Free;
        Response.Free;
      end;
    end;
     
    procedure TLinkExplorer.ExtractLinks(const HTML: string; BaseURL: string;
      var LinkList: TStringList);
    var
      Regex: TRegEx;
      Match: TMatch;
      Link: string;
    begin
      // Regex simple pour capturer href="..." dans les balises <a>.
      Regex := TRegEx.Create('<a\s+(?:[^>]*?\s+)?href="([^"]*)"', [roIgnoreCase]);
      Match := Regex.Match(HTML);
      while Match.Success do
      begin
        Link := Match.Groups[1].Value;
     
        // Normalise les URLs relatives en les transformant en URLs absolues basées sur BaseURL.
        if not Link.StartsWith('http') then
        begin
          if Link.StartsWith('/') then
            Link := BaseURL + Link
          else
            Link := BaseURL + '/' + Link;
        end;
     
        // Ajoute le lien s'il n'a pas encore été visité (évite doublons dans la file).
        if not VisitedLinks.ContainsKey(Link) then
          LinkList.Add(Link);
     
        Match := Match.NextMatch;
      end;
    end;
     
    // Enlève certains paramètres d'URL (ex : ?w=) pour normaliser les sources médias.
    function RemoveURLParams(const URL: string): string;
    begin
      Result := URL;
      if Pos('?w=', Result) > 0 then
        Result := Copy(Result, 1, Pos('?w=', Result) - 1);
    end;
     
    procedure TLinkExplorer.ExtractMediaSources(const HTML: string; BaseURL: string;
      var ImageList, DocList: TStringList);
    var
      RegexImg, RegexDoc: TRegEx;
      Match: TMatch;
      Source: string;
    begin
      // Regex pour trouver les balises <img src="..."> pointant vers des extensions d'image courantes.
      RegexImg := TRegEx.Create
        ('<img\s+[^>]*src="([^"]+\.(jpg|jpeg|png|gif|bmp|webp|svg))"',
        [roIgnoreCase]);
      Match := RegexImg.Match(HTML);
      while Match.Success do
      begin
        Source := RemoveURLParams(Match.Groups[1].Value);
     
        // Gère les sources relatives.
        if not Source.StartsWith('http') then
          Source := BaseURL + Source;
     
        // Vérifie la présence d'une extension avant d'ajouter.
        if TPath.GetExtension(Source) <> '' then
          ImageList.Add(Source);
     
        Match := Match.NextMatch;
      end;
     
      // Regex pour trouver les liens vers PDF, HTML, CSS (documents intéressants).
      RegexDoc := TRegEx.Create('<a\s+[^>]*href="([^"]+\.(pdf|html|css))"',
        [roIgnoreCase]);
      Match := RegexDoc.Match(HTML);
      while Match.Success do
      begin
        Source := RemoveURLParams(Match.Groups[1].Value);
     
        if not Source.StartsWith('http') then
          Source := BaseURL + Source;
     
        if TPath.GetExtension(Source) <> '' then
          DocList.Add(Source);
     
        Match := Match.NextMatch;
      end;
    end;
     
    // Recherche un nœud enfant direct d'un parent dont le texte correspond exactement.
    // Retourne nil si non trouvé.
    function FindTreeNode(ParentNode: TTreeNode; const Text: string): TTreeNode;
    var
      Node: TTreeNode;
    begin
      Result := nil;
      Node := ParentNode.getFirstChild;
      while Node <> nil do
      begin
        if Node.Text = Text then
        begin
          Result := Node;
          Exit;
        end;
        Node := Node.getNextSibling;
      end;
    end;
     
    procedure TLinkExplorer.AddFilesToTreeView(ImageList, DocList: TStringList;
      TreeView: TTreeView; FileLabel: TLabel);
    var
      i: Integer;
      RootNode, ImagesNode, DocsNode: TTreeNode;
      AddedCount: Integer;
      // Compteurs locaux pour afficher le nombre par section dans le TreeView.
      ImageCount, DocCount: Integer;
      Node: TTreeNode;
    begin
      AddedCount := 0;
     
      // Récupère le nœud racine ou le crée si absent.
      RootNode := TreeView.Items.GetFirstNode;
      if RootNode = nil then
        RootNode := TreeView.Items.Add(nil, 'Fichiers trouvés');
     
      // Cherche ou crée le sous-nœud "Images" (on compare seulement le préfixe pour conserver le compteur).
      ImagesNode := nil;
      Node := RootNode.getFirstChild;
      while Node <> nil do
      begin
        if SameText(Copy(Node.Text, 1, Length('Images')), 'Images') then
        begin
          ImagesNode := Node;
          Break;
        end;
        Node := Node.getNextSibling;
      end;
      if ImagesNode = nil then
        ImagesNode := TreeView.Items.AddChild(RootNode, 'Images');
     
      // Cherche ou crée le sous-nœud "Documents".
      DocsNode := nil;
      Node := RootNode.getFirstChild;
      while Node <> nil do
      begin
        if SameText(Copy(Node.Text, 1, Length('Documents')), 'Documents') then
        begin
          DocsNode := Node;
          Break;
        end;
        Node := Node.getNextSibling;
      end;
      if DocsNode = nil then
        DocsNode := TreeView.Items.AddChild(RootNode, 'Documents');
     
      // Ajoute les images sous le nœud "Images" en évitant les doublons.
      for i := 0 to ImageList.Count - 1 do
      begin
        if FindTreeNode(ImagesNode, ImageList[i]) = nil then
        begin
          TreeView.Items.AddChild(ImagesNode, ImageList[i]);
          Inc(AddedCount);
        end;
      end;
     
      // Ajoute les documents sous le nœud "Documents" en évitant les doublons.
      for i := 0 to DocList.Count - 1 do
      begin
        if FindTreeNode(DocsNode, DocList[i]) = nil then
        begin
          TreeView.Items.AddChild(DocsNode, DocList[i]);
          Inc(AddedCount);
        end;
      end;
     
      // Mise à jour du compteur global de fichiers et du label associé.
      if AddedCount > 0 then
      begin
        Inc(FileCount, AddedCount);
        if Assigned(FileLabel) then
          FileLabel.Caption := 'Fichiers trouvés : ' + IntToStr(FileCount);
      end;
     
      // Calcul du nombre d'enfants directs pour ImagesNode (pour afficher un compteur local).
      ImageCount := 0;
      Node := ImagesNode.getFirstChild;
      while Node <> nil do
      begin
        Inc(ImageCount);
        Node := Node.getNextSibling;
      end;
     
      // Calcul du nombre d'enfants directs pour DocsNode.
      DocCount := 0;
      Node := DocsNode.getFirstChild;
      while Node <> nil do
      begin
        Inc(DocCount);
        Node := Node.getNextSibling;
      end;
     
      // Met à jour le texte des nœuds pour inclure le compteur local.
      ImagesNode.Text := 'Images : ' + IntToStr(ImageCount);
      DocsNode.Text := 'Documents : ' + IntToStr(DocCount);
    end;
     
    procedure TLinkExplorer.ExploreLinksRecursive(const URL: string;
      ListBox: TListBox; TreeView: TTreeView; LabelCounter, FileLabel: TLabel;
      Depth: Integer);
    var
      HTMLContent: string;
      Links, Images, Docs: TStringList;
      i: Integer;
    begin
      // Vérifie le drapeau d'arrêt demandé par l'UI.
      if StopProcess then
        Exit;
     
      // Si la profondeur est atteinte, arrête la récursion.
      if Depth <= 0 then
        Exit;
     
      // Si l'URL a déjà été visitée, éviter de la revisiter.
      if VisitedLinks.ContainsKey(URL) then
        Exit;
     
      // Marque l'URL comme visitée et incrémente le compteur global.
      VisitedLinks.Add(URL, True);
      Inc(TotalLinks);
     
      // Permet au thread de l'interface utilisateur de traiter les messages
      // (utile si la méthode est appelée depuis le thread principal).
      Application.ProcessMessages;
      if Assigned(LabelCounter) then
        LabelCounter.Caption := 'Liens parcourus : ' + IntToStr(TotalLinks);
     
      // Récupère le contenu HTML de la page.
      HTMLContent := GetWebContent(URL);
      if HTMLContent = '' then
        Exit;
     
      // Création des listes locales pour stocker les résultats d'analyse.
      Links := TStringList.Create;
      Images := TStringList.Create;
      Docs := TStringList.Create;
      try
        // Extrait les liens et médias depuis le contenu HTML.
        ExtractLinks(HTMLContent, URL, Links);
        ExtractMediaSources(HTMLContent, URL, Images, Docs);
     
        // Ajoute l'URL parcourue à la ListBox pour visibilité.
        ListBox.Items.Add(URL);
     
        // Ajoute les images et documents trouvés dans le TreeView.
        AddFilesToTreeView(Images, Docs, TreeView, FileLabel);
     
        // Appel récursif sur chaque lien trouvé tant que la profondeur le permet.
        for i := 0 to Links.Count - 1 do
        begin
          if StopProcess then
            Exit;
          ExploreLinksRecursive(Links[i], ListBox, TreeView, LabelCounter,
            FileLabel, Depth - 1);
        end;
      finally
        // Libération des listes temporaires.
        Links.Free;
        Images.Free;
        Docs.Free;
      end;
    end;
     
    procedure TLinkExplorer.ExploreLinks(const URL: string; ListBox: TListBox;
      TreeView: TTreeView; LabelCounter, FileLabel: TLabel; MaxDepth: Integer);
    begin
      // Initialise l'état interne de l'explorateur pour une nouvelle session.
      VisitedLinks := TDictionary<string, Boolean>.Create;
      TotalLinks := 0;
      FileCount := 0;
      StopProcess := False;
      try
        // Initialise le libellé des fichiers si fourni.
        if Assigned(FileLabel) then
          FileLabel.Caption := 'Fichiers trouvés : 0';
     
        // Lance la recherche récursive depuis l'URL racine.
        ExploreLinksRecursive(URL, ListBox, TreeView, LabelCounter, FileLabel,
          MaxDepth);
      finally
        // Libère le dictionnaire des liens visités.
        VisitedLinks.Free;
      end;
    end;
     
    end.
    Nom : Capture d'�cran 2025-10-11 173015.png
Affichages : 614
Taille : 82,1 Ko

    Code Source : LinkExplorer.zip
    Vous ne pouvez pas faire confiance � un code que vous n'avez pas totalement r�dig� vous-m�me.
    Ce n�est pas un bogue - c�est une fonctionnalit� non document�e.

  2. #2
    Membre exp�riment�
    Avatar de XeGregory
    Homme Profil pro
    Passionn� par la programmation
    Inscrit en
    Janvier 2017
    Messages
    541
    D�tails du profil
    Informations personnelles :
    Sexe : Homme
    �ge : 36
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activit� : Passionn� par la programmation
    Secteur : High Tech - Mat�riel informatique

    Informations forums :
    Inscription : Janvier 2017
    Messages : 541
    Par d�faut Link Explorer v2
    Nom : Capture d'�cran 2025-10-12 111737.png
Affichages : 427
Taille : 74,7 Ko

    Code Source : Link Explorer v2.zip
    Vous ne pouvez pas faire confiance � un code que vous n'avez pas totalement r�dig� vous-m�me.
    Ce n�est pas un bogue - c�est une fonctionnalit� non document�e.

  3. #3
    Membre exp�riment�
    Avatar de XeGregory
    Homme Profil pro
    Passionn� par la programmation
    Inscrit en
    Janvier 2017
    Messages
    541
    D�tails du profil
    Informations personnelles :
    Sexe : Homme
    �ge : 36
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activit� : Passionn� par la programmation
    Secteur : High Tech - Mat�riel informatique

    Informations forums :
    Inscription : Janvier 2017
    Messages : 541
    Par d�faut Link Explorer v3
    THttpClientPool

    • Pool fixe d�instances THTTPClient cr�� par Create(MaxClients).
    • Synchronisation : TCriticalSection pour la liste FClients + TEvent pour attendre la disponibilit�.
    • API : Acquire (bloque en boucle courte si vide), Release (remet le client et signale l��v�nement).


    TLinkExplorer

    • �tat : VisitedLinks: TDictionary<string,Boolean>, compteurs (TotalLinks, FileCount, BrokenCount), StopProcess.
    • Param�tres : RequestTimeoutMs, RequestDelayMs, SameDomainOnly, FPoolSize.
    • API publique : ConfigureCrawl(..., APoolSize), ExploreLinks(startURL, ListView, TreeView, LabelCounter, FileLabel, MaxDepth), StopExploration.
    • Fonctions internes : GetWebContent (GET via pool), IsFileAvailable (HEAD puis GET Range si n�cessaire), ExtractLinks/ExtractMediaSources (regex), AddFilesToTreeView, AddBrokenLink, IsSameDomain, EnsurePoolCreated.


    Nom : Video_2025_10_14-1_edit_0.gif
Affichages : 241
Taille : 1,16 Mo

    Code Source : LinkExplorer v3.zip
    Vous ne pouvez pas faire confiance � un code que vous n'avez pas totalement r�dig� vous-m�me.
    Ce n�est pas un bogue - c�est une fonctionnalit� non document�e.

  4. #4
    Expert �minent
    Avatar de ShaiLeTroll
    Homme Profil pro
    D�veloppeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    14 115
    D�tails du profil
    Informations personnelles :
    Sexe : Homme
    �ge : 44
    Localisation : France, Seine Saint Denis (�le de France)

    Informations professionnelles :
    Activit� : D�veloppeur C++\Delphi
    Secteur : High Tech - �diteur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 14 115
    Par d�faut
    Co�ncidence, j'ai un ami qui tente d'utiliser HTTrack pour un site en d�clin, nom de domaine en expiration.


    Tr�s int�ressant ce TLinkExplorer, pour le moment, je lui avais cod� que l'extraction des images publiques (non connect�), j'ai nettement plus de mal pour g�rer un cookie pour les images priv�es (connect� avec son login) au point d'utiliser un TWebBrowser/OnDocumentComplete ce qui est tr�s lent.
    Si tu sais g�rer le cookie sans TWebBrowser avec TIdHTTP (�a existe mais j'ai carr�ment pas le temps), je suis preneur.


    Code : S�lectionner tout - Visualiser dans une fen�tre � part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    unit WebImageDownloader_Processor;
     
    interface
     
    uses
      System.Classes, System.Contnrs;
     
    type
      TWebImageDownloaderProcessorClass = class of TWebImageDownloaderProcessor;
      TWebImageDownloaderProcessor = class(TObject)
      private
        class var FClassList: TClassList;
        class var FWorkDir: string;
        class var FProcesssLinkRecursive: Boolean;
      protected
        class procedure RegisterMe(); virtual; abstract;
        class procedure RegisterClass(AClass: TWebImageDownloaderProcessorClass);
     
        class procedure ProcessContent(const AURL: string; AContent: TStringStream; AProcessImage: Boolean; AProcessLink: Boolean; const ALinkSectionStart, ALinkSectionEnd: string);
        class procedure ProcessImage(const AContent: string; IndexStart, IndexEnd: Integer; AImageURLs: TStringList); virtual;
        class procedure ProcessLink(const AContent: string; IndexStart, IndexEnd: Integer; ALinks: TStringList); virtual;
        class procedure DownloadFile(const AWebDir: string; const AURL: string);
        class procedure GetInternetFile(const AServerName: string; const AURL: string; AStream: TStream); overload;
        class procedure GetInternetFile(const AURL: string; AStream: TStream); overload;
      public
        class function FindClass(const AClassSuffix: string): TWebImageDownloaderProcessorClass;
     
        class procedure ProcessURL(const AURL: string; AProcessImage: Boolean; AProcessLink: Boolean; const ALinkSectionStart, ALinkSectionEnd: string);
     
        class property WorkDir: string read FWorkDir write FWorkDir;
        class property ProcesssLinkRecursive: Boolean read FProcesssLinkRecursive write FProcesssLinkRecursive;
      public
        class destructor Destroy();
      end;
     
    implementation
     
    uses
      System.SysUtils, System.StrUtils,
      IdHTTP, IdSSLOpenSSL, IdSSLOpenSSLHeaders,
      Winapi.WinInet, Winapi.Windows;
     
     
    class destructor TWebImageDownloaderProcessor.Destroy();
    begin
      FreeAndNil(FClassList);
    end;
     
    class procedure TWebImageDownloaderProcessor.DownloadFile(const AWebDir: string; const AURL: string);
     
      function ExtractFileNameFromURL(const FileName: string): string;
      var
        I: Integer;
      begin
        I := FileName.LastDelimiter('/');
        Result := FileName.SubString(I + 1);
        Result := StringReplace(Result, '>', '_', [rfReplaceAll]);
        Result := StringReplace(Result, '<', '_', [rfReplaceAll]);
        Result := StringReplace(Result, ':', '_', [rfReplaceAll]);
        Result := StringReplace(Result, '"', '_', [rfReplaceAll]);
        Result := StringReplace(Result, '/', '_', [rfReplaceAll]);
        Result := StringReplace(Result, '\', '_', [rfReplaceAll]);
        Result := StringReplace(Result, '|', '_', [rfReplaceAll]);
        Result := StringReplace(Result, '?', '_', [rfReplaceAll]);
        Result := StringReplace(Result, '*', '_', [rfReplaceAll]);
        Result := StringReplace(Result, '.jpg_c=2', '.jpg', [rfIgnoreCase]);
      end;
     
      function ExcludeTrailingURL(const S: string): string;
      begin
        Result := S;
        if (Length(Result) >= 1) and (Result[Length(Result)] = '/') then
          SetLength(Result, Length(Result)-1);
      end;
     
    var
      LocalDir, LocalName: string;
      DownloadStream: TFileStream;
      Downloader: TIdHTTP;
    begin
      LocalDir := IncludeTrailingPathDelimiter(FWorkDir) + ExtractFileNameFromURL(ExcludeTrailingURL(AWebDir));
      ForceDirectories(LocalDir);
      LocalName := IncludeTrailingPathDelimiter(LocalDir) + ExtractFileNameFromURL(AURL);
     
      DownloadStream := TFileStream.Create(LocalName, fmCreate);
      try
        Downloader := TIdHTTP.Create(nil);
        try
          if StartsText('https:', AURL) then
            Downloader.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(Downloader);
     
          try
            Downloader.Get(AURL, DownloadStream);
          except
            on E: EIdOSSLUnderlyingCryptoError do
              GetInternetFile(AURL, DownloadStream);
          end;
        finally
          Downloader.Free();
        end;
      finally
        DownloadStream.Free();
      end;
    end;
     
    class function TWebImageDownloaderProcessor.FindClass(const AClassSuffix: string): TWebImageDownloaderProcessorClass;
    var
      I: Integer;
    begin
      Result := nil;
      if Assigned(FClassList) then
        for I := 0 to FClassList.Count - 1 do
          if SameText(FClassList[I].ClassName(), TWebImageDownloaderProcessor.ClassName() + AClassSuffix) then
            Exit(TWebImageDownloaderProcessorClass(FClassList[I]));
    end;
     
    class procedure TWebImageDownloaderProcessor.GetInternetFile(const AURL: string; AStream: TStream);
    var
      I1, I2: Integer;
      ServerName: string;
      URI: string;
    begin
      I1 := Pos('//', AURL);
      Inc(I1, 2);
      I2 := Pos('/', AURL, I1);
      if (I1 > 0) and (I2 > I1) then
      begin
        ServerName := Copy(AURL, I1, I2 - I1);
        URI := Copy(AURL, I2 + 1);
        GetInternetFile(ServerName, URI, AStream);
      end;
    end;
     
    class procedure TWebImageDownloaderProcessor.GetInternetFile(const AServerName: string; const AURL: string; AStream: TStream);
    const
      BufferSize = 1024;
      accept: packed array[0..1] of LPWSTR = (PChar('text/*'), nil); // PCTSTR rgpszAcceptTypes[] = {_T(“text/*”), NULL};
    var
      hSession, hHTTP, hReq : HINTERNET;
      Buffer: array[1..BufferSize] of Byte;
      BufferLen: DWORD;
      sAppName: string;
    begin
      AStream.Size := 0;
      sAppName := ExtractFileName(ParamStr(0));
     
      hSession := InternetOpen(PChar(sAppName), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
      try
        hHTTP := InternetConnect(hSession, PChar(AServerName), INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 1);
        try
          hReq := HttpOpenRequest(hHTTP, PChar('GET'), PChar(AURL), nil, nil, @accept, 0, 1);
          try
            if HttpSendRequest(hReq, nil, 0, nil, 0) then
            begin
              BufferLen := 0;
              repeat
                if InternetReadFile(hReq, @Buffer, BufferSize, BufferLen) then
                  AStream.WriteBuffer(Buffer, BufferLen);
     
              until BufferLen = 0;
            end
            else
              raise Exception.Create('HttpOpenRequest failed. ' + SysErrorMessage(GetLastError));
          finally
            InternetCloseHandle(hReq);
          end;
        finally
          InternetCloseHandle(hHTTP);
        end;
      finally
        InternetCloseHandle(hSession);
      end;
    end;
     
    class procedure TWebImageDownloaderProcessor.ProcessContent(const AURL: string; AContent: TStringStream; AProcessImage: Boolean; AProcessLink: Boolean; const ALinkSectionStart, ALinkSectionEnd: string);
    var
      Content: string;
      iStart, iEnd: Integer;
      Images, Links: TStringList;
      Link: string;
    begin
      Content := AContent.DataString;
      if AProcessLink then
      begin
        iStart := Pos(ALinkSectionStart, Content);
        if iStart > 0 then
        begin
          Inc(iStart, Length(ALinkSectionStart));
          iEnd := Pos(ALinkSectionEnd, Content, iStart);
          if iEnd > 0 then
          begin
            Links := TStringList.Create();
            try
              Links.Duplicates := dupIgnore;
              Links.Sorted := True;
     
              ProcessLink(Content, iStart, iEnd, Links);
              Links.SaveToFile(IncludeTrailingPathDelimiter(FWorkDir) + 'Links.txt');
              for Link in Links do
                ProcessURL(Link, True, FProcesssLinkRecursive, '', '');
            finally
              Links.Free();
            end;
          end
          else
            raise Exception.CreateFmt('End of Section "%s" not found', [ALinkSectionEnd]);
        end
        else
          raise Exception.CreateFmt('Start of Section "%s" not found', [ALinkSectionStart]);
      end;
     
      if AProcessImage then
      begin
        Images := TStringList.Create();
        try
          ProcessImage(Content, 1, Length(Content), Images);
          Images.SaveToFile(IncludeTrailingPathDelimiter(FWorkDir) + 'Images.txt');
          for Link in Images do
            DownloadFile(AURL, Link);
        finally
          Images.Free();
        end;
      end;
     
    end;
     
    class procedure TWebImageDownloaderProcessor.ProcessImage(const AContent: string; IndexStart, IndexEnd: Integer; AImageURLs: TStringList);
    const
      IMG_START = '<img src="';
      IMG_END = '/>';
      IMG_SUB_END = '" ';
    var
      iStart, iEnd, iSub: Integer;
      URL: string;
    begin
      iStart := IndexStart;
      while iStart < IndexEnd do
      begin
        iStart := Pos(IMG_START, AContent, iStart);
        if (iStart > 0) and (iStart <= IndexEnd) then
        begin
          Inc(iStart, Length(IMG_START));
          iEnd := Pos(IMG_END, AContent, iStart);
          if (iEnd > iStart) and (iEnd <= IndexEnd) then
          begin
            URL := Copy(AContent, iStart, iEnd - iStart);
            iSub := Pos(IMG_SUB_END, URL);
            if iSub > 0 then
              URL := Copy(URL, 1, iSub - 1);
            AImageURLs.Add(URL);
          end
          else
            Exit;
        end
        else
          Exit;
     
        iStart := iEnd + Length(IMG_END);
      end;
    end;
     
     
    class procedure TWebImageDownloaderProcessor.ProcessLink(const AContent: string; IndexStart, IndexEnd: Integer; ALinks: TStringList);
    const
      REF_START = '<a href="';
      REF_END = '">';
      REF_SUB_END = '" ';
    var
      iStart, iEnd, iSub: Integer;
      URL: string;
    begin
      iStart := IndexStart;
      while iStart < IndexEnd do
      begin
        iStart := Pos(REF_START, AContent, iStart);
        if (iStart > 0) and (iStart <= IndexEnd) then
        begin
          Inc(iStart, Length(REF_START));
          iEnd := Pos(REF_END, AContent, iStart);
          if (iEnd > iStart) and (iEnd <= IndexEnd) then
          begin
            URL := Copy(AContent, iStart, iEnd - iStart);
            iSub := Pos(REF_SUB_END, URL);
            if iSub > 0 then
              URL := Copy(URL, 1, iSub - 1);
            ALinks.Add(URL);
          end
          else
            Exit;
        end
        else
          Exit;
     
        iStart := iEnd + Length(REF_END);
      end;
    end;
     
     
    class procedure TWebImageDownloaderProcessor.ProcessURL(const AURL: string; AProcessImage: Boolean; AProcessLink: Boolean; const ALinkSectionStart, ALinkSectionEnd: string);
    var
      WebPage: TIdHTTP;
      WebContent: TStringStream;
    begin
      WebPage := TIdHTTP.Create(nil);
      try
        if StartsText('https:', AURL) then
          WebPage.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(WebPage);
     
        WebContent := TStringStream.Create();
        try
          try
            WebPage.Get(AURL, WebContent);
          except
            on E: EIdOSSLUnderlyingCryptoError do
              GetInternetFile(AURL, WebContent);
          end;
          ProcessContent(AURL, WebContent, AProcessImage, AProcessLink, ALinkSectionStart, ALinkSectionEnd);
        finally
          WebContent.Free();
        end;
      finally
        WebPage.Free();
      end;
    end;
     
    class procedure TWebImageDownloaderProcessor.RegisterClass(AClass: TWebImageDownloaderProcessorClass);
    begin
      // Not Thread-Safe !
      if not Assigned(FClassList) then
        FClassList := TClassList.Create();
     
      FClassList.Add(AClass);
    end;
     
    end.
    Code : S�lectionner tout - Visualiser dans une fen�tre � part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    unit WebImageDownloader_WMProcessor;
     
    interface
     
    uses
      System.Classes,
      WebImageDownloader_Processor;
     
    type
      TWebImageDownloaderProcessorWM = class(TWebImageDownloaderProcessor)
      protected
        class procedure RegisterMe(); override;
     
        class procedure ProcessImage(const AContent: string; IndexStart, IndexEnd: Integer; AImageURLs: TStringList); override;
      end;
     
    implementation
     
    uses
      System.SysUtils;
     
    { TWebImageDownloaderProcessorWM }
     
    class procedure TWebImageDownloaderProcessorWM.ProcessImage(const AContent: string; IndexStart, IndexEnd: Integer; AImageURLs: TStringList);
    const
      IMAGE_TAG = 'ZoomImageURLs';
      IMAGE_TAG_OFFSET = '[%d] = "';
      IMAGE_TAG_END = '";';
    var
      iStart, iEnd: Integer;
      iImage: Integer;
      ImageTag, URL: string;
    begin
      iStart := IndexStart;
      iImage := 0;
      while iStart < IndexEnd do
      begin
        ImageTag := IMAGE_TAG + Format(IMAGE_TAG_OFFSET, [iImage]);
        iStart := Pos(ImageTag, AContent, iStart);
        if (iStart > 0) and (iStart <= IndexEnd) then
        begin
          Inc(iStart, Length(ImageTag));
          iEnd := Pos(IMAGE_TAG_END, AContent, iStart);
          if (iEnd > iStart) and (iEnd <= IndexEnd) then
          begin
            URL := Copy(AContent, iStart, iEnd - iStart);
            URL := StringReplace(URL, '\/', '/', [rfReplaceAll]);
            AImageURLs.Add(URL);
            Inc(iImage);
          end
          else
            Exit;
        end
        else
          Exit;
     
        iStart := iEnd + Length(IMAGE_TAG_END);
      end;
    end;
     
    class procedure TWebImageDownloaderProcessorWM.RegisterMe();
    begin
      RegisterClass(Self);
    end;
     
    initialization
      TWebImageDownloaderProcessorWM.RegisterMe();
     
    end.
    Aide via F1 - FAQ - Guide du d�veloppeur Delphi devant un probl�me - Pensez-y !
    Attention Troll M�chant !
    "Quand un homme a faim, mieux vaut lui apprendre � p�cher que de lui donner un poisson" Confucius
    Mieux vaut se taire et para�tre idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la m�diocrit� !

    L'exp�rience, c'est le nom que chacun donne � ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  5. #5
    Membre exp�riment�
    Avatar de XeGregory
    Homme Profil pro
    Passionn� par la programmation
    Inscrit en
    Janvier 2017
    Messages
    541
    D�tails du profil
    Informations personnelles :
    Sexe : Homme
    �ge : 36
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activit� : Passionn� par la programmation
    Secteur : High Tech - Mat�riel informatique

    Informations forums :
    Inscription : Janvier 2017
    Messages : 541
    Par d�faut
    Citation Envoy� par ShaiLeTroll Voir le message
    Si tu sais g�rer le cookie sans TWebBrowser avec TIdHTTP
    Bonjour ShaiLeTroll,

    Tu peut utiliser le composant IdCookieManager, pour la gestion des cookies

    Code : S�lectionner tout - Visualiser dans une fen�tre � part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    procedure TForm1.Button1Click(Sender: TObject);
    var
      Params: TStringList;
      i: Integer;
    begin
      Memo1.Clear;
     
      // Configuration de IdHTTP
      IdHTTP1.CookieManager := IdCookieManager1;
      IdHTTP1.HandleRedirects := True;
     
      Params := TStringList.Create;
      try
        Params.Add('username=monlogin');       
        Params.Add('password=monmotdepasse'); 
     
        // Envoi de la requête POST vers la page de login
        Memo1.Lines.Add('Connexion...');
        Memo1.Lines.Add(IdHTTP1.Post('https://exemple.com/login', Params));
     
        // Affichage des cookies reçus
        Memo1.Lines.Add('Cookies reçus :');
        for i := 0 to IdCookieManager1.CookieCollection.Count - 1 do
          Memo1.Lines.Add(IdCookieManager1.CookieCollection[i].CookieText);
     
        // Requête suivante avec session maintenue
        Memo1.Lines.Add('Accès à l’espace client...');
        Memo1.Lines.Add(IdHTTP1.Get('https://exemple.com/espace-client'));
      finally
        Params.Free;
      end;
    end;
    TWebBrowser/OnDocumentComplete ce qui est tr�s lent.


    J'ai d�j� exp�riment� l'extraction avec un TWebBrowser, mais �a prend une plombe de traiter les donn�es.
    Il vaut mieux utiliser TIdHTTP ou TNetHTTPClient/THTTPClient.

    Un petit ajout d'un t�l�chargement l�-dessus et le tour est jou�

    Nom : Capture d'�cran 2025-10-14 195200.png
Affichages : 185
Taille : 261,7 Ko

    Nom : Capture d'�cran 2025-10-14 202247.png
Affichages : 182
Taille : 94,6 Ko

    Enfin, presque, je veux �valuer la profondeur du site automatiquement.
    Ajouter un respect sur le robot.txt, s'il est pr�sent sur le serveur. (Dev en cour...)
    Un t�l�chargement automatique des fichiers trouv�s. (Dev en cour...)
    Ajout d'une cr�ation de projet (Nouveau, charger) et enregistrement du projet � partir d'un fichier JSON.

    Nom : Capture d'�cran 2025-10-15 072153.png
Affichages : 157
Taille : 92,3 Ko
    Vous ne pouvez pas faire confiance � un code que vous n'avez pas totalement r�dig� vous-m�me.
    Ce n�est pas un bogue - c�est une fonctionnalit� non document�e.

  6. #6
    Membre exp�riment�
    Avatar de XeGregory
    Homme Profil pro
    Passionn� par la programmation
    Inscrit en
    Janvier 2017
    Messages
    541
    D�tails du profil
    Informations personnelles :
    Sexe : Homme
    �ge : 36
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activit� : Passionn� par la programmation
    Secteur : High Tech - Mat�riel informatique

    Informations forums :
    Inscription : Janvier 2017
    Messages : 541
    Par d�faut Link Explorer v4
    Nom : Capture d'�cran 2025-10-16 181332.png
Affichages : 123
Taille : 96,1 Ko

    Code Source : LinkExplorer v4.zip
    Vous ne pouvez pas faire confiance � un code que vous n'avez pas totalement r�dig� vous-m�me.
    Ce n�est pas un bogue - c�est une fonctionnalit� non document�e.

  7. #7
    Membre exp�riment�
    Avatar de XeGregory
    Homme Profil pro
    Passionn� par la programmation
    Inscrit en
    Janvier 2017
    Messages
    541
    D�tails du profil
    Informations personnelles :
    Sexe : Homme
    �ge : 36
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activit� : Passionn� par la programmation
    Secteur : High Tech - Mat�riel informatique

    Informations forums :
    Inscription : Janvier 2017
    Messages : 541
    Par d�faut Link Explorer v4.1
    Modifications apport�es

    - Nouveau cache d�di�
    Ajout de FBrokenLinks: TDictionary<string, Boolean> pour stocker uniquement les URLs corrompues.

    - Marquage des liens corrompus
    MarkBrokenLink enregistre d�sormais dans FBrokenLinks et met � jour le ListView avec "Corrompu".
    Les cas "Corrompu (ignor�)" ajoutent aussi l�URL dans FBrokenLinks.

    - Export CSV
    ExportBrokenLinksToCSV :
    Exporte uniquement les lignes dont Status/DownloadState contiennent "Corrompu".

    - IsSameDomain renforc� (gestion des h�tes, sous-domaines et ports).

    Nom : Capture d'�cran 2025-10-17 064806.png
Affichages : 68
Taille : 103,9 Ko

    Code source : LinkExplorer v4.1.zip
    Vous ne pouvez pas faire confiance � un code que vous n'avez pas totalement r�dig� vous-m�me.
    Ce n�est pas un bogue - c�est une fonctionnalit� non document�e.

+ R�pondre � la discussion
Cette discussion est r�solue.

Discussions similaires

  1. [MySQL] Lien vers page web php incorecte
    Par falltech dans le forum PHP & Base de donn�es
    R�ponses: 2
    Dernier message: 05/10/2010, 15h54
  2. VBA Lien vers page web
    Par bella1 dans le forum VBA Access
    R�ponses: 1
    Dernier message: 09/02/2010, 14h03
  3. Liens vers des Web user controls ?
    Par Invit� dans le forum ASP.NET
    R�ponses: 2
    Dernier message: 19/05/2008, 12h24
  4. [PDF] Ouvrir PDF dans l'explorateur par lien
    Par adrianclowes dans le forum Biblioth�ques et frameworks
    R�ponses: 2
    Dernier message: 17/11/2007, 17h48
  5. Lien vers site Web
    Par titouan07 dans le forum Langage
    R�ponses: 6
    Dernier message: 13/02/2007, 19h39

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo