Debian Codegraph @

README

raw ◀ ▶
1 Debian patch touch this file
1 NAME
2 HTML::Query - jQuery-like selection queries for HTML::Element
3
4 SYNOPSIS
5 Creating an "HTML::Query" object using the Query() constructor
6 subroutine:
7
8 use HTML::Query 'Query';
9
10 # using named parameters
11 $q = Query( text => $text ); # HTML text
12 $q = Query( file => $file ); # HTML file
13 $q = Query( tree => $tree ); # HTML::Element object
14 $q = Query( query => $query ); # HTML::Query object
15 $q = Query(
16 text => $text1, # or any combination
17 text => $text2, # of the above
18 file => $file1,
19 file => $file2,
20 tree => $tree,
21 query => $query,
22 );
23
24 # passing elements as positional arguments
25 $q = Query( $tree ); # HTML::Element object(s)
26 $q = Query( $tree1, $tree2, $tree3, ... );
27
28 # or from one or more existing queries
29 $q = Query( $query1 ); # HTML::Query object(s)
30 $q = Query( $query1, $query2, $query3, ... );
31
32 # or a mixture
33 $q = Query( $tree1, $query1, $tree2, $query2 );
34
35 # the final argument (in all cases) can be a selector
36 my $spec = 'ul.menu li a'; # <ul class="menu">..<li>..<a>
37
38 $q = Query( $tree, $spec );
39 $q = Query( $query, $spec );
40 $q = Query( $tree1, $tree2, $query1, $query2, $spec );
41 $q = Query( text => $text, $spec );
42 $q = Query( file => $file, $spec );
43 $q = Query( tree => $tree, $spec );
44 $q = Query( query => $query, $spec );
45 $q = Query(
46 text => $text,
47 file => $file,
48 # ...etc...
49 $spec
50 );
51
52 Or using the OO new() constructor method (which the Query() subroutine
53 maps onto):
54
55 use HTML::Query;
56
57 $q = HTML::Query->new(
58 # accepts the same arguments as Query()
59 )
60
61 Or by monkey-patching a query() method into HTML::Element.
62
63 use HTML::Query 'query'; # note lower case 'q'
64 use HTML::TreeBuilder;
65
66 # build a tree
67 my $tree = HTML::TreeBuilder->new;
68 $tree->parse_file($filename);
69
70 # call the query() method on any element
71 my $query = $tree->query($spec);
72
73 Once you have a query, you can start selecting elements:
74
75 @r = $q->query('a')->get_elements(); # all <a>...</a> elements
76 @r = $q->query('a#menu')->get_elements(); # all <a> with "menu" id
77 @r = $q->query('#menu')->get_elements(); # all elements with "menu" id
78 @r = $q->query('a.menu')->get_elements(); # all <a> with "menu" class
79 @r = $q->query('.menu')->get_elements(); # all elements with "menu" class
80 @r = $q->query('a[href]')->get_elements(); # all <a> with 'href' attr
81 @r = $q->query('a[href=foo]')->get_elements(); # all <a> with 'href="foo"' attr
82
83 # you can specify elements within elements...
84 @r = $q->query('ul.menu li a')->get_elements(); # <ul class="menu">...<li>...<a>
85
86 # and use commas to delimit multiple path specs for different elements
87 @r = $q->query('table tr td a, form input[type=submit]')->get_elements();
88
89 # query() in scalar context returns a new query
90 $r = $q->query('table')->get_elements();; # find all tables
91 $s = $r->query('tr')->get_elements(); # find all rows in all those tables
92 $t = $s->query('td')->get_elements(); # and all cells in those rows...
93
94 Inspecting query elements:
95
96 # get number of elements in query
97 my $size = $q->size
98
99 # get first/last element in query
100 my $first = $q->first;
101 my $last = $q->last;
102
103 # convert query to list or list ref of HTML::Element objects
104 my $list = $q->list; # list ref in scalar context
105 my @list = $q->list; # list in list context
106
107 All other methods are mapped onto the HTML::Element objects in the
108 query:
109
110 print $query->as_trimmed_text; # print trimmed text for each element
111 print $query->as_HTML; # print each element as HTML
112 $query->delete; # call delete() on each element
113
114 DESCRIPTION
115 The "HTML::Query" module is an add-on for the HTML::Tree module set. It
116 provides a simple way to select one or more elements from a tree using a
117 query syntax inspired by jQuery. This selector syntax will be
118 reassuringly familiar to anyone who has ever written a CSS selector.
119
120 "HTML::Query" is not an attempt to provide a complete (or even
121 near-complete) implementation of jQuery in Perl (see Ingy's pQuery
122 module for a more ambitious attempt at that). Rather, it borrows some of
123 the tried and tested selector syntax from jQuery (and CSS) that can
124 easily be mapped onto the "look_down()" method provided by the
125 HTML::Element module.
126
127 Creating a Query
128 The easiest way to create a query is using the exportable Query()
129 subroutine.
130
131 use HTML::Query 'Query'; # note capital 'Q'
132
133 It accepts a "text" or "file" named parameter and will create an
134 "HTML::Query" object from the HTML source text or file, respectively.
135
136 my $query = Query( text => $text );
137 my $query = Query( file => $file );
138
139 This delegates to HTML::TreeBuilder to parse the HTML into a tree of
140 HTML::Element objects. The root element returned is then wrapped in an
141 "HTML::Query" object.
142
143 If you already have one or more HTML::Element objects that you want to
144 query then you can pass them to the Query() subroutine as arguments. For
145 example, you can explicitly use HTML::TreeBuilder to parse an HTML
146 document into a tree:
147
148 use HTML::TreeBuilder;
149 my $tree = HTML::TreeBuilder->new;
150 $tree->parse_file($filename);
151
152 And then create an "HTML::Query" object for the tree either using an
153 explicit "tree" named parameter:
154
155 my $query = Query( tree => $tree );
156
157 Or implicitly using positional arguments.
158
159 my $query = Query( $tree );
160
161 If you want to query across multiple elements, then pass each one as a
162 positional argument.
163
164 my $query = Query( $tree1, $tree2, $tree3 );
165
166 You can also create a new query from one or more existing queries,
167
168 my $query = Query( query => $query ); # named parameter
169 my $query = Query( $query1, $query2 ); # positional arguments.
170
171 You can mix and match these different parameters and positional
172 arguments to create a query across several different sources.
173
174 $q = Query(
175 text => $text1,
176 text => $text2,
177 file => $file1,
178 file => $file2,
179 tree => $tree,
180 query => $query,
181 );
182
183 The Query() subroutine is a simple wrapper around the new() constructor
184 method. You can instantiate your objects manually if you prefer. The
185 new() method accepts the same arguments as for the Query() subroutine
186 (in fact, the Query() subroutine simply forwards all arguments to the
187 new() method).
188
189 use HTML::Query;
190
191 my $query = HTML::Query->new(
192 # same argument format as for Query()
193 );
194
195 A final way to use "HTML::Query" is to have it add a query() method to
196 HTML::Element. The "query" import hook (all lower case) can be specified
197 to make this so.
198
199 use HTML::Query 'query'; # note lower case 'q'
200 use HTML::TreeBuilder;
201
202 my $tree = HTML::TreeBuilder->new;
203 $tree->parse_file($filename);
204
205 # now all HTML::Elements have a query() method
206 my @items = $tree->query('ul li')->get_elements(); # find all list items
207
208 This approach, often referred to as *monkey-patching*, should be used
209 carefully and sparingly. It involves a violation of HTML::Element's
210 namespace that could have unpredictable results with a future version of
211 the module (e.g. one which defines its own "query()" method that does
212 something different). Treat it as something that is great to get a quick
213 job done right now, but probably not something to be used in production
214 code without careful consideration of the implications.
215
216 Selecting Elements
217 Having created an "HTML::Query" object by one of the methods outlined
218 above, you can now fetch descendant elements in the tree using a simple
219 query syntax. For example, to fetch all the "<a>" elements in the tree,
220 you can write:
221
222 @links = $query->query('a')->get_elements();
223
224 Or, if you want the elements that have a specific "class" attribute
225 defined with a value of, say "menu", you can write:
226
227 @links = $query->query('a.menu')->get_elements();
228
229 More generally, you can look for the existence of any attribute and
230 optionally provide a specific value for it.
231
232 @links = $query->query('a[href]')->get_elements(); # any href attribute
233 @links = $query->query('a[href=index.html]')->get_elements(); # specific value
234
235 You can also find an element (or elements) by specifying an id.
236
237 @links = $query->query('#menu')->get_elements(); # any element with id="menu"
238 @links = $query->query('ul#menu')->get_elements(); # ul element with id="menu"
239
240 You can provide multiple selection criteria to find elements within
241 elements within elements, and so on. For example, to find all links in a
242 menu, you can write:
243
244 # matches: <ul class="menu"> <li> <a>
245 @links = $query->query('ul.menu li a')->get_elements();
246
247 You can separate different criteria using commas. For example, to fetch
248 all table rows and "span" elements with a "foo" class:
249
250 @elems = $query->('table tr, span.foo')->get_elements();
251
252 Query Results
253 When called in list context, as shown in the examples above, the query()
254 method returns a list of HTML::Element objects matching the search
255 criteria. In scalar context, the query() method returns a new
256 "HTML::Query" object containing the HTML::Element objects found. You can
257 then call the query() method against that object to further refine the
258 query. The query() method applies the selection to all elements stored
259 in the query.
260
261 my $tables = $query->query('table'); # query for tables
262 my $rows = $tables->query('tr'); # requery for all rows in those tables
263 my $cells = $rows->query('td')->get_elements(); # return back all the cells in those rows
264
265 Inspection Methods
266 The size() method returns the number of elements in the query. The
267 first() and last() methods return the first and last items in the query,
268 respectively.
269
270 if ($query->size) {
271 print "from ", $query->first->as_trimmed_text, " to ", $query->last->as_trimmed_text;
272 }
273
274 If you want to extract the HTML::Element objects from the query you can
275 call the list() method. This returns a list of HTML::Element objects in
276 list context, or a reference to a list in scalar context.
277
278 @elems = $query->list;
279 $elems = $query->list;
280
281 Element Methods
282 Any other methods are automatically applied to each element in the list.
283 For example, to call the "as_trimmed_text()" method on all the
284 HTML::Element objects in the query, you can write:
285
286 print $query->as_trimmed_text;
287
288 In list context, this method returns a list of the return values from
289 calling the method on each element. In scalar context it returns a
290 reference to a list of return values.
291
292 @text_blocks = $query->as_trimmed_text;
293 $text_blocks = $query->as_trimmed_text;
294
295 See HTML::Element for further information on the methods it provides.
296
297 QUERY SYNTAX
298 Basic Selectors
299 element
300 Matches all elements of a particular type.
301
302 @elems = $query->query('table')->get_elements(); # <table>
303
304 #id
305 Matches all elements with a specific id attribute.
306
307 @elems = $query->query('#menu')->get_elements() # <ANY id="menu">
308
309 This can be combined with an element type:
310
311 @elems = $query->query('ul#menu')->get_elements(); # <ul id="menu">
312
313 .class
314 Matches all elements with a specific class attribute.
315
316 @elems = $query->query('.info')->get_elements(); # <ANY class="info">
317
318 This can be combined with an element type and/or element id:
319
320 @elems = $query->query('p.info')->get_elements(); # <p class="info">
321 @elems = $query->query('p#foo.info')->get_elements(); # <p id="foo" class="info">
322 @elems = $query->query('#foo.info')->get_elements(); # <ANY id="foo" class="info">
323
324 The selectors listed above can be combined in a whitespace delimited
325 sequence to select down through a hierarchy of elements. Consider the
326 following table:
327
328 <table class="search">
329 <tr class="result">
330 <td class="value">WE WANT THIS ELEMENT</td>
331 </tr>
332 <tr class="result">
333 <td class="value">AND THIS ONE</td>
334 </tr>
335 ...etc..
336 </table>
337
338 To locate the cells that we're interested in, we can write:
339
340 @elems = $query->query('table.search tr.result td.value')->get_elements();
341
342 Attribute Selectors
343 W3C CSS 2 specification defines new constructs through which to select
344 based on specific attributes within elements. See the following link for
345 the spec: <http://www.w3.org/TR/css3-selectors/#attribute-selectors>
346
347 [attr]
348 Matches elements that have the specified attribute, including any where
349 the attribute has no value.
350
351 @elems = $query->query('[href]')->get_elements(); # <ANY href="...">
352
353 This can be combined with any of the above selectors. For example:
354
355 @elems = $query->query('a[href]')->get_elements(); # <a href="...">
356 @elems = $query->query('a.menu[href]')->get_elements(); # <a class="menu" href="...">
357
358 You can specify multiple attribute selectors. Only those elements that
359 match *all* of them will be selected.
360
361 @elems = $query->query('a[href][rel]')->get_elements(); # <a href="..." rel="...">
362
363 [attr=value]
364 Matches elements that have an attribute set to a specific value. The
365 value can be quoted in either single or double quotes, or left unquoted.
366
367 @elems = $query->query('[href=index.html]')->get_elements();
368 @elems = $query->query('[href="index.html"]')->get_elements();
369 @elems = $query->query("[href='index.html']")->get_elements();
370
371 You can specify multiple attribute selectors. Only those elements that
372 match *all* of them will be selected.
373
374 @elems = $query->query('a[href=index.html][rel=home]')->get_elements();
375
376 [attr|=value]
377 Matches any element X whose foo attribute has a hyphen-separated list of
378 values beginning (from the left) with bar. The value can be quoted in
379 either single or double quotes, or left unquoted.
380
381 @elems = $query->query('[lang|=en]')->get_elements();
382 @elems = $query->query('p[class|="example"]')->get_elements();
383 @elems = $query->query("img[alt|='fig']")->get_elements();
384
385 You can specify multiple attribute selectors. Only those elements that
386 match *all* of them will be selected.
387
388 @elems = $query->query('p[class|="external"][lang|="en"]')->get_elements();
389
390 [attr~=value]
391 Matches any element X whose foo attribute value is a list of
392 space-separated values, one of which is exactly equal to bar. The value
393 can be quoted in either single or double quotes, or left unquoted.
394
395 @elems = $query->query('[lang~=en]')->get_elements();
396 @elems = $query->query('p[class~="example"]')->get_elements();
397 @elems = $query->query("img[alt~='fig']")->get_elements();
398
399 You can specify multiple attribute selectors. Only those elements that
400 match *all* of them will be selected.
401
402 @elems = $query->query('p[class~="external"][lang~="en"]')->get_elements();
403
404 KNOWN BUG: you can't have a "]" character in the attribute value because
405 it confuses the query parser. Fixing this is TODO.
406
407 Universal Selector
408 W3C CSS 2 specification defines a new construct through which to select
409 any element within the document below a given hierarchy.
410
411 http://www.w3.org/TR/css3-selectors/#universal-selector
412
413 @elems = $query->query('*')->get_elements();
414
415 Combinator Selectors
416 W3C CSS 2 specification defines new constructs through which to select
•417 based on hierarchy with the DOM. See the following link for the spec:
418 <http://www.w3.org/TR/css3-selectors/#combinators>
419
420 Immediate Descendents (children)
421 When you combine selectors with whitespace elements are selected if they
422 are descended from the parent in some way. But if you just want to
423 select the children (and not the grandchildren, great-grandchildren,
424 etc) then you can combine the selectors with the ">" character.
425
426 @elems = $query->query('a > img')->get_elements();
427
428 Non-Immediate Descendents
429 If you just want any descendents that aren't children then you can
430 combine selectors with the "*" character.
431
432 @elems = $query->query('div * a')->get_elements();
433
434 Immediate Siblings
435 If you want to use a sibling relationship then you can can join
436 selectors with the "+" character.
437
438 @elems = $query->query('img + span')->get_elements();
439
440 Pseudo-classes
441 W3C CSS 2 and CSS 3 specifications define new concepts of pseudo-classes
442 to permit formatting based on information that lies outside the document
443 tree. See the following link for the most recent spec:
444 <http://www.w3.org/TR/css3-selectors/#pseudo-classes>
445
446 HTML::Query currently has limited support for CSS 2, and no support for
447 CSS 3.
448
449 Patches are *highly* encouraged to help add support here.
450
451 -child pseudo-classes
452 If you want to return child elements within a certain position then
453 -child pseudo-classes (:first-child, :last-child) are what you're
454 looking for.
455
456 @elems = $query->query('table td:first-child')->get_elements;
457
458 Link pseudo-classes: :link and :visited
459 Unsupported.
460
461 The :link pseudo-class is to be implemented, currently unsupported.
462
463 It is not possible to locate :visited outside of a browser context due
464 to it's dynamic nature.
465
466 Dynamic pseudo-classes
467 Unsupported.
468
469 It is not possible to locate these classes(:hover, :active, :focus)
470 outside of a browser context due to their dynamic nature.
471
472 Language pseudo-class
473 Unsupported.
474
475 Functionality for the :lang pseudo-class is largely replicated by using
476 an attribute selector for lang combined with a universal selector query.
477
478 If this is insufficient I'd love to see a patch adding support for it.
479
480 Other pseudo-classes
481 W3C CSS 3 added a number of new behaviors that need support. At this
482 time there is no support for them, but we should work on adding support.
483
484 Patches are very welcome.
485
486 Pseudo-elements
487 W3C CSS 2 and CSS 3 specification defines new concepts of
488 pseudo-elements to permit formatting based on information that lies
489 outside the document tree. See the following link for the most recent
490 spec: <http://www.w3.org/TR/css3-selectors/#pseudo-elements>
491
492 At this time there is no support for pseudo-elements, but we are working
493 on adding support.
494
495 Patches are very welcome.
496
497 Combining Selectors
498 You can combine basic and hierarchical selectors into a single query by
499 separating each part with a comma. The query will select all matching
500 elements for each of the comma-delimited selectors. For example, to find
501 all "a", "b" and "i" elements in a tree:
502
503 @elems = $query->query('a, b, i')->get_elements();
504
505 Each of these selectors can be arbitrarily complex.
506
507 @elems = $query->query(
508 'table.search[width=100%] tr.result[valign=top] td.value,
509 form.search input[type=submit],
510 a[href=index.html]'
511 )->get_elements();
512
513 EXPORT HOOKS
514 Query
515 The "Query()" constructor subroutine (note the capital letter) can be
516 exported as a convenient way to create "HTML::Query" objects. It simply
517 forwards all arguments to the new() constructor method.
518
519 use HTML::Query 'Query';
520
521 my $query = Query( file => $file, 'ul.menu li a' );
522
523 query
524 The "query()" export hook can be called to monkey-patch a query() method
525 into the HTML::Element module.
526
527 This is considered questionable behaviour in polite society which
528 regards it as a violation of the inner sanctity of the HTML::Element.
529
530 But if you're the kind of person that doesn't mind a bit of occasional
531 namespace abuse for the sake of getting the job done, then go right
532 ahead. Just don't blame me if it all blows up later.
533
534 use HTML::Query 'query'; # note lower case 'q'
535 use HTML::TreeBuilder;
536
537 # build a tree
538 my $tree = HTML::TreeBuilder->new;
539 $tree->parse_file($filename);
540
541 # call the query() method on any element
542 my $query = $tree->query('ul li a');
543
544 METHODS
545 The "HTML::Query" object is a subclass of Badger::Base and inherits all
546 of its method.
547
548 new(@elements,$selector)
549 This constructor method is used to create a new "HTML::Query" object. It
550 expects a list of any number (including zero) of HTML::Element or
551 "HTML::Query" objects.
552
553 # single HTML::Element object
554 my $query = HTML::Query->new($elem);
555
556 # multiple element object
557 my $query = HTML::Query->new($elem1, $elem2, $elem3, ...);
558
559 # copy elements from an existing query
560 my $query = HTML::Query->new($another_query);
561
562 # copy elements from several queries
563 my $query = HTML::Query->new($query1, $query2, $query3);
564
565 # or a mixture
566 my $query = HTML::Query->new($elem1, $query1, $elem2, $query3);
567
568 You can also use named parameters to specify an alternate source for a
569 element.
570
571 $query = HTML::Query->new( file => $file );
572 $query = HTML::Query->new( text => $text );
573
574 In this case, the HTML::TreeBuilder module is used to parse the source
575 file or text into a tree of HTML::Element objects.
576
577 For the sake of completeness, you can also specify element trees and
578 queries using named parameters:
579
580 $query = HTML::Query->new( tree => $tree );
581 $query = HTML::Query->new( query => $query );
582
583 You can freely mix and match elements, queries and named sources. The
584 query will be constructed as an aggregate across them all.
585
586 $q = HTML::Query->new(
587 text => $text1,
588 text => $text2,
589 file => $file1,
590 file => $file2,
591 tree => $tree,
592 query => $query1,
593 );
594
595 The final, optional argument can be a selector specification. This is
596 immediately passed to the query() method which will return a new query
597 with only those elements selected.
598
599 my $spec = 'ul.menu li a'; # <ul class="menu">..<li>..<a>
600
601 my $query = HTML::Query->new( $tree, $spec );
602 my $query = HTML::Query->new( text => $text, $spec );
603 my $query = HTML::Query->new(
604 text => $text,
605 file => $file,
606 $spec
607 );
608
609 The list of arguments can also be passed by reference to a list.
610
611 my $query = HTML::Query->new(\@args);
612
613 query($spec)
614 This method locates the descendant elements identified by the $spec
•615 argument for each element in the query. It then internally stores the
616 results for requerying or return. See get_elements().
617
618 my $query = HTML::Query->new(\@args);
619 my $results = $query->query($spec);
620
621 See "QUERY SYNTAX" for the permitted syntax of the $spec argument.
622
623 get_elements()
624 This method returns the stored results from a query. In list context it
625 returns a list of matching HTML::Element objects. In scalar context it
626 returns a reference to the results array.
627
628 my $query = HTML::Query->new(\@args);
629 my $results = $query->query($spec);
630
631 my @elements = $results->query($spec)->get_elements();
632 my $elements = $results->query($spec)->get_elements();
633
634 get_specificity()
635 Calculate the specificity for any given passed selector, a critical
636 factor in determining how best to apply the cascade
637
638 A selector's specificity is calculated as follows:
639
640 * count the number of ID attributes in the selector (= a) * count the
641 number of other attributes and pseudo-classes in the selector (= b) *
642 count the number of element names in the selector (= c) * ignore
643 pseudo-elements.
644
645 The specificity is based only on the form of the selector. In
646 particular, a selector of the form "[id=p33]" is counted as an attribute
647 selector (a=0, b=0, c=1, d=0), even if the id attribute is defined as an
648 "ID" in the source document's DTD.
649
650 See the following spec for additional details:
651 <http://www.w3.org/TR/CSS21/cascade.html#specificity>
652
653 size()
654 Returns the number of elements in the query.
655
656 first()
657 Returns the first element in the query.
658
659 my $elem = $query->first;
660
661 If the query is empty then an exception will be thrown. If you would
662 rather have an undefined value returned then you can use the "try"
663 method inherited from Badger::Base. This effectively wraps the call to
664 "first()" in an "eval" block to catch any exceptions thrown.
665
666 my $elem = $query->try('first') || warn "no first element\n";
667
668 last()
669 Similar to first(), but returning the last element in the query.
670
671 my $elem = $query->last;
672
673 list()
674 Returns a list of the HTML::Element object in the query in list context,
675 or a reference to a list in scalar context.
676
677 my @elems = $query->list;
678 my $elems = $query->list;
679
680 AUTOLOAD
681 The "AUTOLOAD" method maps any other method calls to the HTML::Element
682 objects in the list. When called in list context it returns a list of
683 the values returned from calling the method on each element. In scalar
684 context it returns a reference to a list of return values.
685
686 my @text_blocks = $query->as_trimmed_text;
687 my $text_blocks = $query->as_trimmed_text;
688
689 KNOWN BUGS
690 Attribute Values
691 It is not possible to use "]" in an attribute value. This is due to a
692 limitation in the parser which will be fixed RSN.
693
694 AUTHOR
695 Andy Wardley <http://wardley.org>
696
697 MAINTAINER
698 Kevin Kamel <[email protected]>
699
700 CONTRIBUTORS
701 Vivek Khera <[email protected]> Michael Peters <[email protected]> David Gray
702 <[email protected]>
703
704 COPYRIGHT
705 Copyright (C) 2010 Andy Wardley. All Rights Reserved.
706
707 This module is free software; you can redistribute it and/or modify it
708 under the same terms as Perl itself.
709
710 SEE ALSO
711 HTML::Tree, HTML::Element, HTML::TreeBuilder, pQuery,
712 <http://jQuery.com/>
713