2
0

fpreporthtmlparser.pp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. {
  2. See the section LICENSE/TERMS below for details about the copyright.
  3. TODO:
  4. - OnDone event when parser has finished
  5. }
  6. {
  7. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8. FastHTMLParser unit to parse HTML
  9. (disect html into its tags and text.)
  10. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11. TITLE : Fast HTML Parser (modified)
  12. CLASS : TjsFastHTMLParser
  13. VERSION : 0.5
  14. AUTHOR : James Azarja
  15. http://www.jazarsoft.com/
  16. CONTRIBUTORS : L505
  17. http://z505.com
  18. Graeme Geldenhuys
  19. http://geldenhuys.co.uk
  20. YourName Here...
  21. LEGAL : Copyright (C) 2004 Jazarsoft, All Rights Reserved.
  22. Modified 2005 Lars (L505)
  23. --------------------------------------------------------------------------------
  24. - Modified for use as a pure command line unit (no dialogs) for freepascal.
  25. - Also added UPPERCASE tags so that when you check for <font> it returns all
  26. tags like <FONT> and <FoNt> and <font>
  27. Use it for what reasons:
  28. -make your own web browsers,
  29. -make your own text copies of web pages for caching purposes
  30. -Grab content from websites -without- using regular expressions
  31. -Seems to be MUCH MUCH FASTER than regular expressions, as it is after all
  32. a true parser
  33. -convert website tables into spreadsheets (parse <TD> and <TR>, turn in to
  34. CSV or similar)
  35. -convert websites into text files (parse all text, and tags <BR> <P> )
  36. -convert website tables into CSV/Database (<parse <TD> and <TR>)
  37. -find certain info from a web page.. i.e. all the bold text or hyperlinks in
  38. a page.
  39. -Parse websites remotely from a CGI app using something like Sockets or
  40. Synapse and SynWrap to first get the HTML site. This would allow you to
  41. dynamically parse info from websites and display data on your site in real
  42. time.
  43. -HTML editor.. WYSIWYG or a partial WYSIWYG editor. Ambitious, but possible.
  44. -HTML property editor. Not completely wysiwyg but ability to edit proprties
  45. of tags. Work would need to be done to parse each property in a tag.
  46. --------------------------------------------------------------------------------
  47. LICENSE/TERMS
  48. --------------------------------------------------------------------------------
  49. This code may be used and modified by anyone so long as this header and
  50. copyright information remains intact.
  51. The code is provided "AS-IS" and without WARRANTY OF ANY KIND,
  52. expressed, implied or otherwise, including and without limitation, any
  53. warranty of merchantability or fitness for a particular purpose. 
  54. In no event shall the author be liable for any special, incidental,
  55. indirect or consequential damages whatsoever (including, without
  56. limitation, damages for loss of profits, business interruption, loss
  57. of information, or any other loss), whether or not advised of the
  58. possibility of damage, and on any theory of liability, arising out of
  59. or in connection with the use or inability to use this software.  
  60. --------------------------------------------------------------------------------
  61. HISTORY:
  62. --------------------------------------------------------------------------------
  63. 0.1 - James:
  64. Initial Development
  65. mostly based on Peter Irlam works & ideas
  66. 0.2 - James:
  67. Some minor bug has fixed
  68. 0.3 - James:
  69. Some jsHTMLUtil function bug has been fixed
  70. 0.4 - James:
  71. jsHTMLUtil Tag Attributes bug has been fixed
  72. thanks to Dmitry [[email protected]]
  73. 0.4L.1a - L505:
  74. Made unit work with freepascal, added UPCASE (case insensitive)
  75. exec function
  76. 0.4L.1b - L505:
  77. Changed case insensitive version to a new class instead of
  78. the old ExecUpcase
  79. 0.5 - Graeme Geldenhuys <[email protected]>
  80. New functions to extract attribute details from the tags.
  81. //
  82. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  83. }
  84. {$IFDEF FPC}{$MODE DELPHI}{$H+}{$ENDIF}
  85. // {$DEFINE DEBUGLN_ON}
  86. unit fpReportHTMLParser;
  87. interface
  88. uses
  89. SysUtils;
  90. {$IFDEF DEBUGLN_ON}
  91. // dummy, default debugging
  92. procedure debugproc(s: string);
  93. // for custom debugging, assign this in your units
  94. var debugln: procedure(s: string) = debugproc;
  95. {$ENDIF}
  96. type
  97. // when tag content found in HTML, including names and values
  98. // case insensitive analysis available via NoCaseTag
  99. TOnFoundTag = procedure(NoCaseTag, ActualTag: string) of object;
  100. // when text found in the HTML
  101. TOnFoundText = procedure(Text: string) of object;
  102. // html parser, case insensitive or case sensitive
  103. THTMLParser = class(TObject)
  104. private
  105. FDone: Boolean;
  106. function CopyBuffer(StartIndex: PChar; Length: Integer): string;
  107. public
  108. OnFoundTag: TOnFoundTag;
  109. OnFoundText: TOnFoundText;
  110. Raw: Pchar;
  111. FCurrent : PChar;
  112. constructor Create(sRaw: string);overload;
  113. constructor Create(pRaw: PChar);overload;
  114. procedure Exec;
  115. procedure NilOnFoundTag(NoCaseTag, ActualTag: string);
  116. procedure NilOnFoundText(Text: string);
  117. function CurrentPos : Integer;
  118. property Done: Boolean read FDone write FDone;
  119. public
  120. {**** These are utility function - not used by the HTML parser **** }
  121. { return value of attrib, NAME case ignored, VALUE case preserved }
  122. function GetVal(const tag, attribname_ci: string): string;
  123. { Return tag name, case preserved }
  124. function GetTagName(const Tag: string): string;
  125. { Return name=value pair ignore case of NAME, preserve case of VALUE }
  126. function GetNameValPair(const tag, attribname_ci: string): string;
  127. { Get value of attribute, e.g WIDTH=36 returns 36, preserves case of value.
  128. The value is stripped from wrapped quotes. eg: bgcolor="black" returns 'black'. }
  129. function GetValFromNameVal(const namevalpair: string): string;
  130. end;
  131. implementation
  132. // default debugging, do nothing, let user do his own by assigning DebugLn var
  133. procedure debugproc(s: string);
  134. begin
  135. end;
  136. { THTMLParser }
  137. function THTMLParser.CopyBuffer(StartIndex: PChar; Length: Integer): string;
  138. begin
  139. SetLength(Result, Length);
  140. StrLCopy(@Result[1], StartIndex, Length);
  141. end;
  142. function THTMLParser.GetVal(const tag, attribname_ci: string): string;
  143. var
  144. nameval: string;
  145. begin
  146. result := '';
  147. if tag = '' then exit;
  148. if attribname_ci = '' then exit;
  149. // returns full name=value pair
  150. nameval := GetNameValPair(tag, attribname_ci);
  151. // extracts value portion only
  152. result := GetValFromNameVal(nameval);
  153. end;
  154. function THTMLParser.GetTagName(const tag: string): string;
  155. var
  156. P: Pchar;
  157. S: Pchar;
  158. begin
  159. P := Pchar(tag);
  160. while P^ in ['<',' ',#9] do inc(P);
  161. S := P;
  162. while Not (P^ in [' ','>',#0]) do inc(P);
  163. if P > S then
  164. Result := CopyBuffer( S, P-S);
  165. end;
  166. function THTMLParser.GetNameValPair(const tag, attribname_ci: string): string;
  167. var
  168. P: Pchar;
  169. S: Pchar;
  170. UpperTag,
  171. UpperAttrib: string;
  172. Start: integer;
  173. L: integer;
  174. C: char;
  175. begin
  176. result := '';
  177. if tag = '' then
  178. exit;
  179. if attribname_ci = '' then
  180. exit;
  181. // must be space before case insensitive NAME, i.e. <a HREF= STYLE=
  182. UpperAttrib := ' ' + upcase(attribname_ci);
  183. UpperTag := upcase(Tag);
  184. P := Pchar(UpperTag);
  185. S := StrPos(P, Pchar(UpperAttrib));
  186. if S <> nil then
  187. begin
  188. inc(S); // skip space
  189. P := S;
  190. // Skip until hopefully equal sign
  191. while not (P^ in ['=', ' ', '>', #0]) do
  192. inc(P);
  193. if (P^ = '=') then inc(P);
  194. while not (P^ in [' ','>',#0]) do
  195. begin
  196. if (P^ in ['"','''']) then
  197. begin
  198. C:= P^;
  199. inc(P); { Skip quote }
  200. end
  201. else
  202. C:= ' ';
  203. while not (P^ in [C, '>', #0]) do
  204. Inc(P);
  205. if (P^ <> '>') then inc(P); { Skip current character, except '>' }
  206. break;
  207. end;
  208. L := P - S;
  209. Start := S - Pchar(UpperTag);
  210. P := Pchar(Tag);
  211. S := P;
  212. inc(S, Start);
  213. { we use Trim() because non-ending Name/Value pairs have a trailing space }
  214. result := Trim(CopyBuffer(S, L));
  215. end;
  216. end;
  217. function THTMLParser.GetValFromNameVal(const namevalpair: string): string;
  218. var
  219. P: Pchar;
  220. S: Pchar;
  221. C: Char;
  222. begin
  223. result := '';
  224. if namevalpair = '' then exit;
  225. P := Pchar(namevalpair);
  226. S := StrPos(P, '=');
  227. if S <> nil then
  228. begin
  229. inc(S); // skip equal
  230. P := S; // set P to a character after =
  231. if (P^ in ['"','''']) then
  232. begin
  233. C := P^;
  234. Inc(P); { Skip current character }
  235. end else
  236. C := ' ';
  237. S := P;
  238. while not (P^ in [C, #0]) do
  239. inc(P);
  240. if (P <> S) then
  241. Result := CopyBuffer(S, P - S)
  242. else
  243. Result := '';
  244. end;
  245. end;
  246. constructor THTMLParser.Create(pRaw: Pchar);
  247. begin
  248. if pRaw = '' then exit;
  249. if pRaw = nil then exit;
  250. Raw:= pRaw;
  251. end;
  252. constructor THTMLParser.Create(sRaw: string);
  253. begin
  254. if sRaw = '' then exit;
  255. Raw:= Pchar(sRaw);
  256. end;
  257. { default dummy "do nothing" events if events are unassigned }
  258. procedure THTMLParser.NilOnFoundTag(NoCaseTag, ActualTag: string);
  259. begin
  260. end;
  261. procedure THTMLParser.NilOnFoundText(Text: string);
  262. begin
  263. end;
  264. function THTMLParser.CurrentPos: Integer;
  265. begin
  266. if Assigned(Raw) and Assigned(FCurrent) then
  267. Result:=FCurrent-Raw
  268. else
  269. Result:=0;
  270. end;
  271. procedure THTMLParser.Exec;
  272. var
  273. L: Integer;
  274. TL: Integer;
  275. I: Integer;
  276. TagStart,
  277. TextStart,
  278. P: PChar; // Pointer to current char.
  279. C: Char;
  280. begin
  281. {$IFDEF DEBUGLN_ON}debugln('FastHtmlParser Exec Begin');{$ENDIF}
  282. { set nil events once rather than checking for nil each time tag is found }
  283. if not assigned(OnFoundText) then
  284. OnFoundText:= NilOnFoundText;
  285. if not assigned(OnFoundTag) then
  286. OnFoundTag:= NilOnFoundTag;
  287. TL:= StrLen(Raw);
  288. I:= 0;
  289. P:= Raw;
  290. Done:= False;
  291. if P <> nil then
  292. begin
  293. TagStart:= nil;
  294. repeat
  295. TextStart:= P;
  296. { Get next tag position }
  297. while Not (P^ in [ '<', #0 ]) do
  298. begin
  299. Inc(P); Inc(I);
  300. if I >= TL then
  301. begin
  302. Done:= True;
  303. Break;
  304. end;
  305. end;
  306. { Is there any text before ? }
  307. if (TextStart <> nil) and (P > TextStart) then
  308. begin
  309. L:= P - TextStart;
  310. { Yes, copy to buffer }
  311. FCurrent:=P;
  312. OnFoundText( CopyBuffer(TextStart, L) );
  313. end else
  314. begin
  315. TextStart:= nil;
  316. end;
  317. { No }
  318. if Done then Break;
  319. TagStart:= P;
  320. while Not (P^ in [ '>', #0]) do
  321. begin
  322. // Find string in tag
  323. if (P^ = '"') or (P^ = '''') then
  324. begin
  325. C:= P^;
  326. Inc(P); Inc(I); // Skip current char " or '
  327. // Skip until string end
  328. while Not (P^ in [C, #0]) do
  329. begin
  330. Inc(P);Inc(I);
  331. end;
  332. end;
  333. Inc(P);Inc(I);
  334. if I >= TL then
  335. begin
  336. Done:= True;
  337. Break;
  338. end;
  339. end;
  340. if Done then Break;
  341. { Copy this tag to buffer }
  342. L:= P - TagStart + 1;
  343. FCurrent:=P;
  344. OnFoundTag( uppercase(CopyBuffer(TagStart, L )), CopyBuffer(TagStart, L ) );
  345. Inc(P); Inc(I);
  346. if I >= TL then Break;
  347. until (Done);
  348. end;
  349. {$IFDEF DEBUGLN_ON}debugln('FastHtmlParser Exec End');{$ENDIF}
  350. end;
  351. end.