我有一些 HTML,我需要从页面中提取实际的书面文本。
到目前为止,我已经尝试使用 Web 浏览器并呈现页面,然后转到文档属性并获取文本。这有效,但仅在支持浏览器的情况下(IE com 对象)。问题是我希望它也能够在 wine 下运行,所以我需要一个不使用 IE COM 的解决方案。
必须有一种合理的编程方式来做到这一点。
我有一些 HTML,我需要从页面中提取实际的书面文本。
到目前为止,我已经尝试使用 Web 浏览器并呈现页面,然后转到文档属性并获取文本。这有效,但仅在支持浏览器的情况下(IE com 对象)。问题是我希望它也能够在 wine 下运行,所以我需要一个不使用 IE COM 的解决方案。
必须有一种合理的编程方式来做到这一点。
我不确定在 Delphi 中解析 HTML 的推荐方法是什么,但如果是我,我很想捆绑一份 html2text 的副本(该名称的较旧的C++ 程序或较新的Python 程序)和产生对其中一个的调用。
您可以使用py2exe将 Python html2text 转换为可执行文件。这两个 html2text 程序都在 GPL 下获得许可,但只要您只是将它们的可执行文件与您的应用程序捆绑在一起并根据 GPL 的限制提供它们的源代码,那么您应该没问题。
您可以直接使用 TIdHttp 及其 Get 方法,而不是使用 TWebBrowser。
你得到了 html 字符串。
这是一个很好的简单例程,从 Scalabium 复制:
function StripHTMLTags(const strHTML: string): string;
var
P: PChar;
InTag: Boolean;
i, intResultLength: Integer;
begin
P := PChar(strHTML);
Result := '';
InTag := False;
repeat
case P^ of
'<': InTag := True;
'>': InTag := False;
#13, #10: ; {do nothing}
else
if not InTag then
begin
if (P^ in [#9, #32]) and ((P+1)^ in [#10, #13, #32, #9, '<']) then
else
Result := Result + P^;
end;
end;
Inc(P);
until (P^ = #0);
{convert system characters}
Result := StringReplace(Result, '"', '"', [rfReplaceAll]);
Result := StringReplace(Result, ''', '''', [rfReplaceAll]);
Result := StringReplace(Result, '>', '>', [rfReplaceAll]);
Result := StringReplace(Result, '<', '<', [rfReplaceAll]);
Result := StringReplace(Result, '&', '&', [rfReplaceAll]);
{here you may add another symbols from RFC if you need}
end;
然后,您可以轻松地对其进行修改以完全按照您的意愿进行操作。