Delphi HTMLParser - Sample 1 - Reading tags
Monday, July 30th, 2007HTMLParser is really easy to use. I have made an sample project for anyone who likes to use HTMLParser for their project.
Assume you have downloaded HTMLParser , and have extracted the files into your library directory.
First you need to drop the following items to your form.
- Memo1: TMemo;
- Edit1: TEdit;
- OpenDialog1: TOpenDialog;
- Button1: TButton;
- Button2: TButton;
- txtTitle: TEdit;
- txtDescription: TEdit;
- txtKeywords: TEdit;
- Memo2: TMemo;

2. Add the following code.
- procedure TForm1.Button1Click(Sender: TObject);
- begin
- if (OpenDialog1.Execute) then
- begin
- Memo1.Lines.LoadFromFile(OpenDialog1.FileName);
- end;
- end;
- procedure TForm1.FormCreate(Sender: TObject);
- begin
- fHTML := THTMLObject.Create;
- end;
- procedure TForm1.FormDestroy(Sender: TObject);
- begin
- fHTML.Free;
- end;
- procedure TForm1.Memo1Change(Sender: TObject);
- begin
- fHTML.LoadFromStrings(Memo1.Lines);
- UpdateFields;
- end;
3. Create a new procedure in Form1.
This method is used to make calls to fHTML to get TITLE tag, Description and Keywords meta tag
- procedure TForm1.UpdateFields;
- var
- i: Integer;
- metatag: TTagObject;
- begin
- //Get title content, just like in Javascipt, tagobject has innerText property
- txtTitle.Text := fHTML.TagByName['TITLE'].innerText;
- //Specify which tag we need look for
- fHTML.TagName := 'META';
- // Reset tag array index to first
- fHTML.First;
- // Look for next META tag
- metatag := fHTML.Next;
- while metatag <> nil do
- begin
- if metatag.CompareValue('NAME', 'DESCRIPTION') or metatag.CompareValue('HTTP-EQUIV', 'DESCRIPTION') then
- begin
- txtDescription.Text := metatag.ReadString('CONTENT', '');
- end else
- if metatag.CompareValue('NAME', 'KEYWORDS') or metatag.CompareValue('HTTP-EQUIV', 'KEYWORDS') then
- begin
- txtKeywords.Text := metatag.ReadString('CONTENT', '');
- end;
- metatag := fHTML.Next;
- end;
- end;
4. At this point you can already run this program, you should be able click Browse (button1) to parse any file on your computer or paste the HTML content from clipboard.
The following code is to show you how to get all A tags from an HTML content
- procedure TForm1.Button2Click(Sender: TObject);
- var
- i: Integer;
- metatag: TTagObject;
- begin
- fHTML.TagName := 'A';
- // Reset tag array index to first
- fHTML.First;
- // Look for next A tag
- metatag := fHTML.Next;
- Memo2.Lines.Clear;
- while metatag <> nil do
- begin
- Memo2.Lines.Add(metatag._RS('href', '(empty url)'));
- metatag := fHTML.Next;
- end;
- end;

