Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

709 lines
26 KiB

  1. #Time-stamp: "2001-03-10 23:19:11 MST" -*-Text-*-
  2. # This document contains text in Perl "POD" format.
  3. # Use a POD viewer like perldoc or perlman to render it.
  4. =head1 NAME
  5. HTML::Tree::Scanning -- article: "Scanning HTML"
  6. =head1 SYNOPSIS
  7. # This an article, not a module.
  8. =head1 DESCRIPTION
  9. The following article by Sean M. Burke first appeared in I<The Perl
  10. Journal> #19 and is copyright 2000 The Perl Journal. It appears
  11. courtesy of Jon Orwant and The Perl Journal. This document may be
  12. distributed under the same terms as Perl itself.
  13. =head1 Scanning HTML
  14. -- Sean M. Burke
  15. In I<The Perl Journal> issue 17, Ken MacFarlane's article "Parsing
  16. HTML with HTML::Parser" describes how the HTML::Parser module scans
  17. HTML source as a stream of start-tags, end-tags, text, comments, etc.
  18. In TPJ #18, my "Trees" article kicked around the idea of tree-shaped
  19. data structures. Now I'll try to tie it together, in a discussion of
  20. HTML trees.
  21. The CPAN module HTML::TreeBuilder takes the
  22. tags that HTML::Parser picks out, and builds a parse tree -- a
  23. tree-shaped network of objects...
  24. =over
  25. Footnote:
  26. And if you need a quick explanation of objects, see my TPJ17 article "A
  27. User's View of Object-Oriented Modules"; or go whole hog and get Damian
  28. Conway's excellent book I<Object-Oriented Perl>, from Manning
  29. Publications.
  30. =back
  31. ...representing the structured content of the HTML document. And once
  32. the document is parsed as a tree, you'll find the common tasks
  33. of extracting data from that HTML document/tree to be quite
  34. straightforward.
  35. =head2 HTML::Parser, HTML::TreeBuilder, and HTML::Element
  36. You use HTML::TreeBuilder to make a parse tree out of an HTML source
  37. file, by simply saying:
  38. use HTML::TreeBuilder;
  39. my $tree = HTML::TreeBuilder->new();
  40. $tree->parse_file('foo.html');
  41. and then C<$tree> contains a parse tree built from the HTML source from
  42. the file "foo.html". The way this parse tree is represented is with a
  43. network of objects -- C<$tree> is the root, an element with tag-name
  44. "html", and its children typically include a "head" and "body" element,
  45. and so on. Elements in the tree are objects of the class
  46. HTML::Element.
  47. So, if you take this source:
  48. <html><head><title>Doc 1</title></head>
  49. <body>
  50. Stuff <hr> 2000-08-17
  51. </body></html>
  52. and feed it to HTML::TreeBuilder, it'll return a tree of objects that
  53. looks like this:
  54. html
  55. / \
  56. head body
  57. / / | \
  58. title "Stuff" hr "2000-08-17"
  59. |
  60. "Doc 1"
  61. This is a pretty simple document, but if it were any more complex,
  62. it'd be a bit hard to draw in that style, since it's sprawl left and
  63. right. The same tree can be represented a bit more easily sideways,
  64. with indenting:
  65. . html
  66. . head
  67. . title
  68. . "Doc 1"
  69. . body
  70. . "Stuff"
  71. . hr
  72. . "2000-08-17"
  73. Either way expresses the same structure. In that structure, the root
  74. node is an object of the class HTML::Element
  75. =over
  76. Footnote:
  77. Well actually, the root is of the class HTML::TreeBuilder, but that's
  78. just a subclass of HTML::Element, plus the few extra methods like
  79. C<parse_file> that elaborate the tree
  80. =back
  81. , with the tag name "html", and with two children: an HTML::Element
  82. object whose tag names are "head" and "body". And each of those
  83. elements have children, and so on down. Not all elements (as we'll
  84. call the objects of class HTML::Element) have children -- the "hr"
  85. element doesn't. And note all nodes in the tree are elements -- the
  86. text nodes ("Doc 1", "Stuff", and "2000-08-17") are just strings.
  87. Objects of the class HTML::Element each have three noteworthy attributes:
  88. =over
  89. =item C<_tag> -- (best accessed as C<$e-E<gt>tag>)
  90. this element's tag-name, lowercased (e.g., "em" for an "em" element).
  91. =over
  92. Footnote: Yes, this is misnamed. In proper SGML terminology, this is
  93. instead called a "GI", short for "generic identifier"; and the term
  94. "tag" is used for a token of SGML source that represents either
  95. the start of an element (a start-tag like "<em lang='fr'>") or the end
  96. of an element (an end-tag like "</em>". However, since more people
  97. claim to have been abducted by aliens than to have ever seen the
  98. SGML standard, and since both encounters typically involve a feeling of
  99. "missing time", it's not surprising that the terminology of the SGML
  100. standard is not closely followed.
  101. =back
  102. =item C<_parent> -- (best accessed as C<$e-E<gt>parent>)
  103. the element that is C<$obj>'s parent, or undef if this element is the
  104. root of its tree.
  105. =item C<_content> -- (best accessed as C<$e-E<gt>content_list>)
  106. the list of nodes (i.e., elements or text segments) that are C<$e>'s
  107. children.
  108. =back
  109. Moreover, if an element object has any attributes in the SGML sense of
  110. the word, then those are readable as C<$e-E<gt>attr('name')> -- for
  111. example, with the object built from having parsed "E<lt>a
  112. B<id='foo'>E<gt>barE<lt>/aE<gt>", C<$e-E<gt>attr('id')> will return
  113. the string "foo". Moreover, C<$e-E<gt>tag> on that object returns the
  114. string "a", C<$e-E<gt>content_list> returns a list consisting of just
  115. the single scalar "bar", and C<$e-E<gt>parent> returns the object
  116. that's this node's parent -- which may be, for example, a "p" element.
  117. And that's all that there is to it -- you throw HTML
  118. source at TreeBuilder, and it returns a tree built of HTML::Element
  119. objects and some text strings.
  120. However, what do you I<do> with a tree of objects? People code
  121. information into HTML trees not for the fun of arranging elements, but
  122. to represent the structure of specific text and images -- some text is
  123. in this "li" element, some other text is in that heading, some
  124. images are in that other table cell that has those attributes, and so on.
  125. Now, it may happen that you're rendering that whole HTML tree into some
  126. layout format. Or you could be trying to make some systematic change to
  127. the HTML tree before dumping it out as HTML source again. But, in my
  128. experience, by far the most common programming task that Perl
  129. programmers face with HTML is in trying to extract some piece
  130. of information from a larger document. Since that's so common (and
  131. also since it involves concepts that are basic to more complex tasks),
  132. that is what the rest of this article will be about.
  133. =head2 Scanning HTML trees
  134. Suppose you have a thousand HTML documents, each of them a press
  135. release. They all start out:
  136. [...lots of leading images and junk...]
  137. <h1>ConGlomCo to Open New Corporate Office in Ougadougou</h1>
  138. BAKERSFIELD, CA, 2000-04-24 -- ConGlomCo's vice president in charge
  139. of world conquest, Rock Feldspar, announced today the opening of a
  140. new office in Ougadougou, the capital city of Burkino Faso, gateway
  141. to the bustling "Silicon Sahara" of Africa...
  142. [...etc...]
  143. ...and what you've got to do is, for each document, copy whatever text
  144. is in the "h1" element, so that you can, for example, make a table of
  145. contents of it. Now, there are three ways to do this:
  146. =over
  147. =item * You can just use a regexp to scan the file for a text pattern.
  148. For many very simple tasks, this will do fine. Many HTML documents are,
  149. in practice, very consistently formatted as far as placement of
  150. linebreaks and whitespace, so you could just get away with scanning the
  151. file like so:
  152. sub get_heading {
  153. my $filename = $_[0];
  154. local *HTML;
  155. open(HTML, $filename)
  156. or die "Couldn't open $filename);
  157. my $heading;
  158. Line:
  159. while(<HTML>) {
  160. if( m{<h1>(.*?)</h1>}i ) { # match it!
  161. $heading = $1;
  162. last Line;
  163. }
  164. }
  165. close(HTML);
  166. warn "No heading in $filename?"
  167. unless defined $heading;
  168. return $heading;
  169. }
  170. This is quick and fast, but awfully fragile -- if there's a newline in
  171. the middle of a heading's text, it won't match the above regexp, and
  172. you'll get an error. The regexp will also fail if the "h1" element's
  173. start-tag has any attributes. If you have to adapt your code to fit
  174. more kinds of start-tags, you'll end up basically reinventing part of
  175. HTML::Parser, at which point you should probably just stop, and use
  176. HTML::Parser itself:
  177. =item * You can use HTML::Parser to scan the file for an "h1" start-tag
  178. token, then capture all the text tokens until the "h1" close-tag. This
  179. approach is extensively covered in the Ken MacFarlane's TPJ17 article
  180. "Parsing HTML with HTML::Parser". (A variant of this approach is to use
  181. HTML::TokeParser, which presents a different and rather handier
  182. interface to the tokens that HTML::Parser picks out.)
  183. Using HTML::Parser is less fragile than our first approach, since it's
  184. not sensitive to the exact internal formatting of the start-tag (much
  185. less whether it's split across two lines). However, when you need more
  186. information about the context of the "h1" element, or if you're having
  187. to deal with any of the tricky bits of HTML, such as parsing of tables,
  188. you'll find out the flat list of tokens that HTML::Parser returns
  189. isn't immediately useful. To get something useful out of those tokens,
  190. you'll need to write code that knows some things about what elements
  191. take no content (as with "hr" elements), and that a "</p>" end-tags
  192. are omissible, so a "<p>" will end any currently
  193. open paragraph -- and you're well on your way to pointlessly
  194. reinventing much of the code in HTML::TreeBuilder
  195. =over
  196. Footnote:
  197. And, as the person who last rewrote that module, I can attest that it
  198. wasn't terribly easy to get right! Never underestimate the perversity
  199. of people coding HTML.
  200. =back
  201. , at which point you should probably just stop, and use
  202. HTML::TreeBuilder itself:
  203. =item * You can use HTML::Treebuilder, and scan the tree of element
  204. objects that you get back.
  205. =back
  206. The last approach, using HTML::TreeBuilder, is the diametric opposite of
  207. first approach: The first approach involves just elementary Perl and one
  208. regexp, whereas the TreeBuilder approach involves being at home with
  209. the concept of tree-shaped data structures and modules with
  210. object-oriented interfaces, as well as with the particular interfaces
  211. that HTML::TreeBuilder and HTML::Element provide.
  212. However, what the TreeBuilder approach has going for it is that it's
  213. the most robust, because it involves dealing with HTML in its "native"
  214. format -- it deals with the tree structure that HTML code represents,
  215. without any consideration of how the source is coded and with what
  216. tags omitted.
  217. So, to extract the text from the "h1" elements of an HTML document:
  218. sub get_heading {
  219. my $tree = HTML::TreeBuilder->new;
  220. $tree->parse_file($_[0]); # !
  221. my $heading;
  222. my $h1 = $tree->look_down('_tag', 'h1'); # !
  223. if($h1) {
  224. $heading = $h1->as_text; # !
  225. } else {
  226. warn "No heading in $_[0]?";
  227. }
  228. $tree->delete; # clear memory!
  229. return $heading;
  230. }
  231. This uses some unfamiliar methods that need explaning. The
  232. C<parse_file> method that we've seen before, builds a tree based on
  233. source from the file given. The C<delete> method is for marking a
  234. tree's contents as available for garbage collection, when you're done
  235. with the tree. The C<as_text> method returns a string that contains
  236. all the text bits that are children (or otherwise descendants) of the
  237. given node -- to get the text content of the C<$h1> object, we could
  238. just say:
  239. $heading = join '', $h1->content_list;
  240. but that will work only if we're sure that the "h1" element's children
  241. will be only text bits -- if the document contained:
  242. <h1>Local Man Sees <cite>Blade</cite> Again</h1>
  243. then the sub-tree would be:
  244. . h1
  245. . "Local Man Sees "
  246. . cite
  247. . "Blade"
  248. . " Again'
  249. so C<join '', $h1-E<gt>content_list> will be something like:
  250. Local Man Sees HTML::Element=HASH(0x15424040) Again
  251. whereas C<$h1-E<gt>as_text> would yield:
  252. Local Man Sees Blade Again
  253. and depending on what you're doing with the heading text, you might
  254. want the C<as_HTML> method instead. It returns the (sub)tree
  255. represented as HTML source. C<$h1-E<gt>as_HTML> would yield:
  256. <h1>Local Man Sees <cite>Blade</cite> Again</h1>
  257. However, if you wanted the contents of C<$h1> as HTML, but not the
  258. C<$h1> itself, you could say:
  259. join '',
  260. map(
  261. ref($_) ? $_->as_HTML : $_,
  262. $h1->content_list
  263. )
  264. This C<map> iterates over the nodes in C<$h1>'s list of children; and
  265. for each node that's just a text bit (as "Local Man Sees " is), it just
  266. passes through that string value, and for each node that's an actual
  267. object (causing C<ref> to be true), C<as_HTML> will used instead of the
  268. string value of the object itself (which would be something quite
  269. useless, as most object values are). So that C<as_HTML> for the "cite"
  270. element will be the string "<cite>BladeE<lt>/cite>". And then,
  271. finally, C<join> just puts into one string all the strings that the
  272. C<map> returns.
  273. Last but not least, the most important method in our C<get_heading> sub
  274. is the C<look_down> method. This method looks down at the subtree
  275. starting at the given object (C<$h1>), looking for elements that meet
  276. criteria you provide.
  277. The criteria are specified in the method's argument list. Each
  278. criterion can consist of two scalars, a key and a value, which express
  279. that you want elements that have that attribute (like "_tag", or
  280. "src") with the given value ("h1"); or the criterion can be a
  281. reference to a subroutine that, when called on the given element,
  282. returns true if that is a node you're looking for. If you specify
  283. several criteria, then that's taken to mean that you want all the
  284. elements that each satisfy I<all> the criteria. (In other words,
  285. there's an "implicit AND".)
  286. And finally, there's a bit of an optimization -- if you call the
  287. C<look_down> method in a scalar context, you get just the I<first> node
  288. (or undef if none) -- and, in fact, once C<look_down> finds that first
  289. matching element, it doesn't bother looking any further.
  290. So the example:
  291. $h1 = $tree->look_down('_tag', 'h1');
  292. returns the first element at-or-under C<$tree> whose C<"_tag">
  293. attribute has the value C<"h1">.
  294. =head2 Complex Criteria in Tree Scanning
  295. Now, the above C<look_down> code looks like a lot of bother, with
  296. barely more benefit than just grepping the file! But consider if your
  297. criteria were more complicated -- suppose you found that some of the
  298. press releases that you were scanning had several "h1" elements,
  299. possibly before or after the one you actually want. For example:
  300. <h1><center>Visit Our Corporate Partner
  301. <br><a href="/dyna/clickthru"
  302. ><img src="/dyna/vend_ad"></a>
  303. </center></h1>
  304. <h1><center>ConGlomCo President Schreck to Visit Regional HQ
  305. <br><a href="/photos/Schreck_visit_large.jpg"
  306. ><img src="/photos/Schreck_visit.jpg"></a>
  307. </center></h1>
  308. Here, you want to ignore the first "h1" element because it contains an
  309. ad, and you want the text from the second "h1". The problem is in
  310. formalizing the way you know that it's an ad. Since ad banners are
  311. always entreating you to "visit" the sponsoring site, you could exclude
  312. "h1" elements that contain the word "visit" under them:
  313. my $real_h1 = $tree->look_down(
  314. '_tag', 'h1',
  315. sub {
  316. $_[0]->as_text !~ m/\bvisit/i
  317. }
  318. );
  319. The first criterion looks for "h1" elements, and the second criterion
  320. limits those to only the ones whose text content doesn't match
  321. C<m/\bvisit/>. But unfortunately, that won't work for our example,
  322. since the second "h1" mentions "ConGlomCo President Schreck to
  323. I<Visit> Regional HQ".
  324. Instead you could try looking for the first "h1" element that
  325. doesn't contain an image:
  326. my $real_h1 = $tree->look_down(
  327. '_tag', 'h1',
  328. sub {
  329. not $_[0]->look_down('_tag', 'img')
  330. }
  331. );
  332. This criterion sub might seem a bit odd, since it calls C<look_down>
  333. as part of a larger C<look_down> operation, but that's fine. Note that
  334. when considered as a boolean value, a C<look_down> in a scalar context
  335. value returns false (specifically, undef) if there's no matching element
  336. at or under the given element; and it returns the first matching
  337. element (which, being a reference and object, is always a true value),
  338. if any matches. So, here,
  339. sub {
  340. not $_[0]->look_down('_tag', 'img')
  341. }
  342. means "return true only if this element has no 'img' element as
  343. descendants (and isn't an 'img' element itself)."
  344. This correctly filters out the first "h1" that contains the ad, but it
  345. also incorrectly filters out the second "h1" that contains a
  346. non-advertisement photo besides the headline text you want.
  347. There clearly are detectable differences between the first and second
  348. "h1" elements -- the only second one contains the string "Schreck", and
  349. we could just test for that:
  350. my $real_h1 = $tree->look_down(
  351. '_tag', 'h1',
  352. sub {
  353. $_[0]->as_text =~ m{Schreck}
  354. }
  355. );
  356. And that works fine for this one example, but unless all thousand of
  357. your press releases have "Schreck" in the headline, that's just not a
  358. general solution. However, if all the ads-in-"h1"s that you want to
  359. exclude involve a link whose URL involves "/dyna/", then you can use
  360. that:
  361. my $real_h1 = $tree->look_down(
  362. '_tag', 'h1',
  363. sub {
  364. my $link = $_[0]->look_down('_tag','a');
  365. return 1 unless $link;
  366. # no link means it's fine
  367. return 0 if $link->attr('href') =~ m{/dyna/};
  368. # a link to there is bad
  369. return 1; # otherwise okay
  370. }
  371. );
  372. Or you can look at it another way and say that you want the first "h1"
  373. element that either contains no images, or else whose image has a "src"
  374. attribute whose value contains "/photos/":
  375. my $real_h1 = $tree->look_down(
  376. '_tag', 'h1',
  377. sub {
  378. my $img = $_[0]->look_down('_tag','img');
  379. return 1 unless $img;
  380. # no image means it's fine
  381. return 1 if $img->attr('src') =~ m{/photos/};
  382. # good if a photo
  383. return 0; # otherwise bad
  384. }
  385. );
  386. Recall that this use of C<look_down> in a scalar context means to return
  387. the first element at or under C<$tree> that matches all the criteria.
  388. But if you notice that you can formulate criteria that'll match several
  389. possible "h1" elements, some of which may be bogus but the I<last> one
  390. of which is always the one you want, then you can use C<look_down> in a
  391. list context, and just use the last element of that list:
  392. my @h1s = $tree->look_down(
  393. '_tag', 'h1',
  394. ...maybe more criteria...
  395. );
  396. die "What, no h1s here?" unless @h1s;
  397. my $real_h1 = $h1s[-1]; # last or only
  398. =head2 A Case Study: Scanning Yahoo News's HTML
  399. The above (somewhat contrived) case involves extracting data from a
  400. bunch of pre-existing HTML files. In that sort of situation, if your
  401. code works for all the files, then you know that the code I<works> --
  402. since the data it's meant to handle won't go changing or growing; and,
  403. typically, once you've used the program, you'll never need to use it
  404. again.
  405. The other kind of situation faced in many data extraction tasks is
  406. where the program is used recurringly to handle new data -- such as
  407. from ever-changing Web pages. As a real-world example of this,
  408. consider a program that you could use (suppose it's crontabbed) to
  409. extract headline-links from subsections of Yahoo News
  410. (C<http://dailynews.yahoo.com/>).
  411. Yahoo News has several subsections:
  412. =over
  413. =item http://dailynews.yahoo.com/h/tc/ for technology news
  414. =item http://dailynews.yahoo.com/h/sc/ for science news
  415. =item http://dailynews.yahoo.com/h/hl/ for health news
  416. =item http://dailynews.yahoo.com/h/wl/ for world news
  417. =item http://dailynews.yahoo.com/h/en/ for entertainment news
  418. =back
  419. and others. All of them are built on the same basic HTML template --
  420. and a scarily complicated template it is, especially when you look at
  421. it with an eye toward making up rules that will select where the real
  422. headline-links are, while screening out all the links to other parts of
  423. Yahoo, other news services, etc. You will need to puzzle
  424. over the HTML source, and scrutinize the output of
  425. C<$tree-E<gt>dump> on the parse tree of that HTML.
  426. Sometimes the only way to pin down what you're after is by position in
  427. the tree. For example, headlines of interest may be in the third
  428. column of the second row of the second table element in a page:
  429. my $table = ( $tree->look_down('_tag','table') )[1];
  430. my $row2 = ( $table->look_down('_tag', 'tr' ) )[1];
  431. my $col3 = ( $row2->look-down('_tag', 'td') )[2];
  432. ...then do things with $col3...
  433. Or they may be all the links in a "p" element that has at least three
  434. "br" elements as children:
  435. my $p = $tree->look_down(
  436. '_tag', 'p',
  437. sub {
  438. 2 < grep { ref($_) and $_->tag eq 'br' }
  439. $_[0]->content_list
  440. }
  441. );
  442. @links = $p->look_down('_tag', 'a');
  443. But almost always, you can get away with looking for properties of the
  444. of the thing itself, rather than just looking for contexts. Now, if
  445. you're lucky, the document you're looking through has clear semantic
  446. tagging, such is as useful in CSS -- note the
  447. class="headlinelink" bit here:
  448. <a href="...long_news_url..." class="headlinelink">Elvis
  449. seen in tortilla</a>
  450. If you find anything like that, you could leap right in and select
  451. links with:
  452. @links = $tree->look_down('class','headlinelink');
  453. Regrettably, your chances of seeing any sort of semantic markup
  454. principles really being followed with actual HTML are pretty thin.
  455. =over
  456. Footnote:
  457. In fact, your chances of finding a page that is simply free of HTML
  458. errors are even thinner. And surprisingly, sites like Amazon or Yahoo
  459. are typically worse as far as quality of code than personal sites
  460. whose entire production cycle involves simply being saved and uploaded
  461. from Netscape Composer.
  462. =back
  463. The code may be sort of "accidentally semantic", however -- for example,
  464. in a set of pages I was scanning recently, I found that looking for
  465. "td" elements with a "width" attribute value of "375" got me exactly
  466. what I wanted. No-one designing that page ever conceived of
  467. "width=375" as I<meaning> "this is a headline", but if you impute it
  468. to mean that, it works.
  469. An approach like this happens to work for the Yahoo News code, because
  470. the headline-links are distinguished by the fact that they (and they
  471. alone) contain a "b" element:
  472. <a href="...long_news_url..."><b>Elvis seen in tortilla</b></a>
  473. or, diagrammed as a part of the parse tree:
  474. . a [href="...long_news_url..."]
  475. . b
  476. . "Elvis seen in tortilla"
  477. A rule that matches these can be formalized as "look for any 'a'
  478. element that has only one daugher node, which must be a 'b' element".
  479. And this is what it looks like when cooked up as a C<look_down>
  480. expression and prefaced with a bit of code that retrieves the text of
  481. the given Yahoo News page and feeds it to TreeBuilder:
  482. use strict;
  483. use HTML::TreeBuilder 2.97;
  484. use LWP::UserAgent;
  485. sub get_headlines {
  486. my $url = $_[0] || die "What URL?";
  487. my $response = LWP::UserAgent->new->request(
  488. HTTP::Request->new( GET => $url )
  489. );
  490. unless($response->is_success) {
  491. warn "Couldn't get $url: ", $response->status_line, "\n";
  492. return;
  493. }
  494. my $tree = HTML::TreeBuilder->new();
  495. $tree->parse($response->content);
  496. $tree->eof;
  497. my @out;
  498. foreach my $link (
  499. $tree->look_down( # !
  500. '_tag', 'a',
  501. sub {
  502. return unless $_[0]->attr('href');
  503. my @c = $_[0]->content_list;
  504. @c == 1 and ref $c[0] and $c[0]->tag eq 'b';
  505. }
  506. )
  507. ) {
  508. push @out, [ $link->attr('href'), $link->as_text ];
  509. }
  510. warn "Odd, fewer than 6 stories in $url!" if @out < 6;
  511. $tree->delete;
  512. return @out;
  513. }
  514. ...and add a bit of code to actually call that routine and display the
  515. results...
  516. foreach my $section (qw[tc sc hl wl en]) {
  517. my @links = get_headlines(
  518. "http://dailynews.yahoo.com/h/$section/"
  519. );
  520. print
  521. $section, ": ", scalar(@links), " stories\n",
  522. map((" ", $_->[0], " : ", $_->[1], "\n"), @links),
  523. "\n";
  524. }
  525. And we've got our own headline-extractor service! This in and of
  526. itself isn't no amazingly useful (since if you want to see the
  527. headlines, you I<can> just look at the Yahoo News pages), but it could
  528. easily be the basis for quite useful features like filtering the
  529. headlines for matching certain keywords of interest to you.
  530. Now, one of these days, Yahoo News will decide to change its HTML
  531. template. When this happens, this will appear to the above program as
  532. there being no links that meet the given criteria; or, less likely,
  533. dozens of erroneous links will meet the criteria. In either case, the
  534. criteria will have to be changed for the new template; they may just
  535. need adjustment, or you may need to scrap them and start over.
  536. =head2 I<Regardez, duvet!>
  537. It's often quite a challenge to write criteria to match the desired
  538. parts of an HTML parse tree. Very often you I<can> pull it off with a
  539. simple C<$tree-E<gt>look_down('_tag', 'h1')>, but sometimes you do
  540. have to keep adding and refining criteria, until you might end up with
  541. complex filters like what I've shown in this article. The
  542. benefit to learning how to deal with HTML parse trees is that one main
  543. search tool, the C<look_down> method, can do most of the work, making
  544. simple things easy, while still making hard things possible.
  545. B<[end body of article]>
  546. =head2 [Author Credit]
  547. Sean M. Burke (C<[email protected]>) is the current maintainer of
  548. C<HTML::TreeBuilder> and C<HTML::Element>, both originally by
  549. Gisle Aas.
  550. Sean adds: "I'd like to thank the folks who listened to me ramble
  551. incessantly about HTML::TreeBuilder and HTML::Element at this year's Yet
  552. Another Perl Conference and O'Reilly Open Source Software Convention."
  553. =head1 BACK
  554. Return to the L<HTML::Tree|HTML::Tree> docs.
  555. =cut