我不想使用twebbrowser, 有谁知道获得网站标题的其他方法?
答案 0 :(得分:11)
您可以使用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.
答案 1 :(得分:5)
这完全取决于网站如何设置标题。
<title>
标签不是唯一的方式,您还有JavaScript等等。
最好是将网页封装在网络浏览器中(例如TWebBrowser
),然后从那里抓取标题。
This page有一些线索。
- 的Jeroen
答案 2 :(得分:1)
继续使用birger的想法并使代码类似于RRUZ,使用Indy(组件TidHTTP),相同的例程可以看到类似于此:
function GetHTMLTitle(const Url:string):string;
const
TitleTagBegin='<title>';
TitleTagEnd ='</title>';
var
idH:TidHTTP;
i,f:integer;
begin
idH := TidHTTP.Create();
try
Result := idH.Get(Trim(URL));
// Search theTAGS
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;
finally
IdH.Free;
end;
end;
此致
答案 3 :(得分:0)
您也可以使用Indy TIdHTTP组件,并在答案中使用与RRUZ相同的方法。
答案 4 :(得分:0)
我有一个解析器(ATagParser),使这种事情变得微不足道。这是一种商业产品,但几年前我把它从市场上拿走了。我仍然积极地使用它并开发它并将它发送给任何要求的人。只要给予信用,它就可以用于个人或商业用途。
顺便说一下,用POS查找标签的想法一切都很好,但它会遗漏带有属性的标题标签 - 是的,标题标签可以有属性(dir,lang等......)
会在给出的其他选项中失败。
答案 5 :(得分:0)
下面的功能还可以检测类似的标题
<title class="notranslate">Title</title>
功能如下:
function GetHTMLTitle(const HTML:string):string;
var
tagstart: int64;
tagstop: int64;
titlestop: int64;
temp:string;
titletext: string;
begin
Result:='';
tagstart:=pos('<title',lowercase(html));
if tagstart>0 then
begin
temp:=copy(html,tagstart);
tagstop:=pos('>',temp);
if tagstop>0 then
begin
temp:=copy(temp,tagstop+1);
titlestop:=pos('</title>',lowercase(temp));
if titlestop>0 then
begin
titletext:=copy(temp,1,titlestop-1);
Result:=titletext;
end;
end;
end;
end;