我不想使用 twebbrowser,
有人知道获取网站标题的其他方法吗?

最佳答案

您可以使用 InternetOpenUrl InternetReadFile 函数获取网页内容,然后查找 <title> 标签。

检查此示例应用程序。

程序 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.

关于delphi - 如何从Delphi获取网站标题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4966888/

10-11 04:38