Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get website title from Delphi?

Tags:

delphi

i don't want to use twebbrowser, anyone know other metod for getting the title of a website?

like image 958
gultekin Avatar asked Nov 29 '22 17:11

gultekin


1 Answers

You can get the content of the webpage using the InternetOpenUrl and InternetReadFile functions and then seek for the <title> tag.

check this sample app.

program GetTitleHTML;

{$APPTYPE CONSOLE}

uses
  WinInet,
  StrUtils,
  SysUtils;

function GetHTMLTitle(const Url:string):string;
const
BuffSize     = 64*1024;
TitleTagBegin='<title>';
TitleTagEnd  ='</title>';
var
  hInter   : HINTERNET;
  UrlHandle: HINTERNET;
  BytesRead: Cardinal;
  Buffer   : Pointer;
  i,f      : Integer;
begin
  Result:='';
  hInter := InternetOpen('', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if Assigned(hInter) then
  begin
    GetMem(Buffer,BuffSize);
    try
       UrlHandle := InternetOpenUrl(hInter, PChar(Url), nil, 0, INTERNET_FLAG_RELOAD,0);
       try
        if Assigned(UrlHandle) then
        begin
          InternetReadFile(UrlHandle, Buffer, BuffSize, BytesRead);
          if BytesRead>0 then
          begin
            SetString(Result, PAnsiChar(Buffer), BytesRead);
            i:=Pos(TitleTagBegin,Result);
            if i>0 then
            begin
              f:=PosEx(TitleTagEnd,Result,i+Length(TitleTagBegin));
              Result:=Copy(Result,i+Length(TitleTagBegin),f-i-Length(TitleTagBegin));
            end;
          end;
        end;
       finally
         InternetCloseHandle(UrlHandle);
       end;
    finally
      FreeMem(Buffer);
    end;
    InternetCloseHandle(hInter);
  end
end;

begin
  try
     Writeln(GetHTMLTitle('http://stackoverflow.com/questions/4966888/how-to-get-website-title-from-delphi'));
     Writeln(GetHTMLTitle('http://www.google.com/'));
     Writeln(GetHTMLTitle('http://stackoverflow.com/questions/tagged/delphi'));
     Readln;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.
like image 176
RRUZ Avatar answered Dec 09 '22 15:12

RRUZ