delphi html parser
代碼是改自原wr960204的 HtmlParser ,因爲自己的需求需要對 html 進行修改操作,但無奈只支持讀取操作,所以在此基礎上做了修改並命名爲HtmlParserEx.pas與之區別。
IHtmlElement和THtmlElement的改變:
1、Attributes屬性增加Set方法
2、TagName屬性增加Set方法
3、增加Parent屬性
4、增加RemoveAttr方法
5、增加Remove方法
6、增加RemoveChild方法
7、增加Find方法,此爲SimpleCSSSelector的一個另名
8、_GetHtml不再直接附加FOrignal屬性值,而是使用GetSelfHtml重新對修改後的元素進行賦值操作,並更新FOrignal的值
9、增加Text屬性
IHtmlElementList和THtmlElementList的改變:
1、增加RemoveAll方法
2、增加Remove方法
3、增加Each方法
4、增加Text屬性
修改後的新功能的一些使用法
IHtmlElement
EL.Attributes[‘class’] := ‘xxxx’;
EL.TagName = 'a';
EL.Remove; // 移除自己
EL.RemoveChild(El2);
El.Find('a');
IHtmlElementList
// 移除選擇的元素
LHtml.Find(‘a’).RemoveAll;
// 查找並遍瀝
// LHtml.Find(‘a’).Each(
procedure(AIndex: Integer; AEl: IHtmlElement)
begin
Writeln(‘Index=’, AIndex, ‘, href=’, AEl.Attributes[‘href’]);
end);
// 直接輸出,僅選中的第一個元素
Writeln(LHtml.Find(‘title’).Text);
// 從文件加載示例
procedure Test;
var
LHtml: IHtmlElement;
LList: IHtmlElementList;
LStrStream: TStringStream;
begin
LStrStream := TStringStream.Create(’’, TEncoding.UTF8);
try
LStrStream.LoadFromFile(‘view-source_https___github.com_ying32_htmlparser.html’);
LHtml := ParserHTML(LStrStream.DataString);
if LHtml <> nil then
begin
LList := LHtml.SimpleCSSSelector(‘a’);
for LHtml in LList do
Writeln(‘url:’, lhtml.Attributes[‘href’]);
end;
finally
LStrStream.Free;
end;
end;
源代碼下載
https://github.com/ying32/htmlparser