1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
|
# NAME
Web::Query - Yet another scraping library like jQuery
# VERSION
version 1.01
# SYNOPSIS
```perl
use Web::Query;
wq('http://www.w3.org/TR/html401/')
->find('div.head dt')
->each(sub {
my $i = shift;
printf("%d %s\n", $i+1, $_->text);
});
```
# DESCRIPTION
Web::Query is a yet another scraping framework, have a jQuery like interface.
Yes, I know Ingy's [pQuery](https://metacpan.org/pod/pQuery). But it's just alpha quality. It doesn't work.
Web::Query built at top of the CPAN modules, [HTML::TreeBuilder::XPath](https://metacpan.org/pod/HTML%3A%3ATreeBuilder%3A%3AXPath), [LWP::UserAgent](https://metacpan.org/pod/LWP%3A%3AUserAgent), and [HTML::Selector::XPath](https://metacpan.org/pod/HTML%3A%3ASelector%3A%3AXPath).
So, this module uses [HTML::Selector::XPath](https://metacpan.org/pod/HTML%3A%3ASelector%3A%3AXPath) and only supports the CSS 3
selector supported by that module.
Web::Query doesn't support jQuery's extended queries(yet?). If a selector is
passed as a scalar ref, it'll be taken as a straight XPath expression.
```
$wq( '<div><p>hello</p><p>there</p></div>' )->find( 'p' ); # css selector
$wq( '<div><p>hello</p><p>there</p></div>' )->find( \'/div/p' ); # xpath selector
```
**THIS LIBRARY IS UNDER DEVELOPMENT. ANY API MAY CHANGE WITHOUT NOTICE**.
# FUNCTIONS
- `wq($stuff)`
This is a shortcut for `Web::Query->new($stuff)`. This function is exported by default.
# METHODS
## CONSTRUCTORS
- my $q = Web::Query->new($stuff, \\%options )
Create new instance of Web::Query. You can make the instance from URL(http, https, file scheme), HTML in string, URL in string, [URI](https://metacpan.org/pod/URI) object, `undef`, and either one
[HTML::Element](https://metacpan.org/pod/HTML%3A%3AElement) object or an array ref of them.
```
# all valid creators
$q = Web::Query->new( 'http://techblog.babyl.ca' );
$q = Web::Query->new( '<p>foo</p>' );
$q = Web::Query->new( undef );
```
This method throw the exception on unknown $stuff.
This method returns undefined value on non-successful response with URL.
Currently, the only two valid options are _indent_, which will be used as
the indentation string if the object is printed, and _no\_space\_compacting_,
which will prevent the compaction of whitespace characters in text blocks.
- my $q = Web::Query->new\_from\_element($element: HTML::Element)
Create new instance of Web::Query from instance of [HTML::Element](https://metacpan.org/pod/HTML%3A%3AElement).
- `my $q = Web::Query->new_from_html($html: Str)`
Create new instance of Web::Query from HTML.
- my $q = Web::Query->new\_from\_url($url: Str)
Create new instance of Web::Query from URL.
If the response is not success(It means /^20\[0-9\]$/), this method returns undefined value.
You can get a last result of response, use the `$Web::Query::RESPONSE`.
Here is a best practical code:
```perl
my $url = 'http://example.com/';
my $q = Web::Query->new_from_url($url)
or die "Cannot get a resource from $url: " . Web::Query->last_response()->status_line;
```
- my $q = Web::Query->new\_from\_file($file\_name: Str)
Create new instance of Web::Query from file name.
## TRAVERSING
### add
Returns a new object augmented with the new element(s).
- add($html)
An HTML fragment to add to the set of matched elements.
- add(@elements)
One or more @elements to add to the set of matched elements.
@elements that already are part of the set are not added a second time.
```perl
my $group = $wq->find('#foo'); # collection has 1 element
$group = $group->add( '#bar', $wq ); # 2 elements
$group->add( '#foo', $wq ); # still 2 elements
```
- add($wq)
An existing Web::Query object to add to the set of matched elements.
- add($selector, $context)
$selector is a string representing a selector expression to find additional elements to add to the set of matched elements.
$context is the point in the document at which the selector should begin matching
### contents
Get the immediate children of each element in the set of matched elements, including text and comment nodes.
### each
Visit each nodes. `$i` is a counter value, 0 origin. `$elem` is iteration item.
`$_` is localized by `$elem`.
```perl
$q->each(sub { my ($i, $elem) = @_; ... })
```
### end
Back to the before context like jQuery.
### filter
Reduce the elements to those that pass the function's test.
```perl
$q->filter(sub { my ($i, $elem) = @_; ... })
```
### find
Get the descendants of each element in the current set of matched elements, filtered by a selector.
```perl
my $q2 = $q->find($selector); # $selector is a CSS3 selector.
```
**NOTE** If you want to match the element itself, use ["filter"](#filter).
**INCOMPATIBLE CHANGE**
From v0.14 to v0.19 (inclusive) find() also matched the element itself, which is not jQuery compatible.
You can achieve that result using `filter()`, `add()` and `find()`:
```perl
my $wq = wq('<div class="foo"><p class="foo">bar</p></div>'); # needed because we don't have a global document like jQuery does
print $wq->filter('.foo')->add($wq->find('.foo'))->as_html; # <div class="foo"><p class="foo">bar</p></div><p class="foo">bar</p>
```
### first
Return the first matching element.
This method constructs a new Web::Query object from the first matching element.
### last
Return the last matching element.
This method constructs a new Web::Query object from the last matching element.
### match($selector)
Returns a boolean indicating if the elements match the `$selector`.
In scalar context returns only the boolean for the first element.
For the reverse of `not()`, see `filter()`.
### not($selector)
Returns all the elements not matching the `$selector`.
```perl
# $do_for_love will be every thing, except #that
my $do_for_love = $wq->find('thing')->not('#that');
```
### and\_back
Add the previous set of elements to the current one.
```
# get the h1 plus everything until the next h1
$wq->find('h1')->next_until('h1')->and_back;
```
### map
Creates a new array with the results of calling a provided function on every element.
```perl
$q->map(sub { my ($i, $elem) = @_; ... })
```
### parent
Get the parent of each element in the current set of matched elements.
### prev
Get the previous node of each element in the current set of matched elements.
```perl
my $prev = $q->prev;
```
### next
Get the next node of each element in the current set of matched elements.
```perl
my $next = $q->next;
```
### next\_until( $selector )
Get all subsequent siblings, up to (but not including) the next node matched `$selector`.
## MANIPULATION
### add\_class
Adds the specified class(es) to each of the set of matched elements.
```
# add class 'foo' to <p> elements
wq('<div><p>foo</p><p>bar</p></div>')->find('p')->add_class('foo');
```
### toggle\_class( @classes )
Toggles the given class or classes on each of the element. I.e., if the element had the class, it'll be removed,
and if it hadn't, it'll be added.
Classes are toggled once, no matter how many times they appear in the argument list.
```
$q->toggle_class( 'foo', 'foo', 'bar' );
# equivalent to
$q->toggle_class('foo')->toggle_class('bar');
# and not
$q->toggle_class('foo')->toggle_class('foo')->toggle_class('bar');
```
### after
Insert content, specified by the parameter, after each element in the set of matched elements.
```
wq('<div><p>foo</p></div>')->find('p')
->after('<b>bar</b>')
->end
->as_html; # <div><p>foo</p><b>bar</b></div>
```
The content can be anything accepted by ["new"](#new).
### append
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
```
wq('<div></div>')->append('<p>foo</p>')->as_html; # <div><p>foo</p></div>
```
The content can be anything accepted by ["new"](#new).
### as\_html
Returns the string representations of either the first or all elements,
depending if called in list or scalar context.
If given an argument `join`, the string representations of the elements
will be concatenated with the given string.
```perl
wq( '<div><p>foo</p><p>bar</p></div>' )
->find('p')
->as_html( join => '!' );
# <p>foo</p>!<p>bar</p>
```
### ` attr `
Get/set attribute values.
In getter mode, it'll return either the values of the attribute
for all elements of the set, or only the first one depending of the calling context.
```perl
my @values = $q->attr('style'); # style of all elements
my $first_value = $q->attr('style'); # style of first element
```
In setter mode, it'll set attributes value for all elements, and return back
the original object for easy chaining.
```perl
$q->attr( 'alt' => 'a picture' )->find( ... );
# can pass more than 1 element too
$q->attr( alt => 'a picture', src => 'file:///...' );
```
The value passed for an attribute can be a code ref. In that case,
the code will be called with `$_` set to the current attribute value.
If the code modifies `$_`, the attribute will be updated with the new value.
```perl
$q->attr( alt => sub { $_ ||= 'A picture' } );
```
### ` id `
Get/set the elements's id attribute.
In getter mode, it behaves just like `attr()`.
In setter mode, it behaves like `attr()`, but with the following exceptions.
If the attribute value is a scalar, it'll be only assigned to
the first element of the set (as ids are supposed to be unique), and the returned object will only contain
that first element.
```perl
my $first_element = $q->id('the_one');
```
It's possible to set the ids of all the elements by passing a sub to `id()`. The sub is given the same arguments as for
`each()`, and its return value is taken to be the new id of the elements.
```perl
$q->id( sub { my $i = shift; 'foo_' . $i } );
```
### ` name `
Get/set the elements's 'name' attribute.
```perl
my $name = $q->name; # equivalent to $q->attr( 'name' );
$q->name( 'foo' ); # equivalent to $q->attr( name => 'foo' );
```
### ` data `
Get/set the elements's 'data-\*name\*' attributes.
```perl
my $data = $q->data('foo'); # equivalent to $q->attr( 'data-foo' );
$q->data( 'foo' => 'bar' ); # equivalent to $q->attr( 'data-foo' => 'bar' );
```
### tagname
Get/Set the tag name of elements.
```perl
my $name = $q->tagname;
$q->tagname($new_name);
```
### before
Insert content, specified by the parameter, before each element in the set of matched elements.
```
wq('<div><p>foo</p></div>')->find('p')
->before('<b>bar</b>')
->end
->as_html; # <div><b>bar</b><p>foo</p></div>
```
The content can be anything accepted by ["new"](#new).
### clone
Create a deep copy of the set of matched elements.
### detach
Remove the set of matched elements from the DOM.
### has\_class
Determine whether any of the matched elements are assigned the given class.
### ` html `
Get/Set the innerHTML.
```perl
my @html = $q->html();
my $html = $q->html(); # 1st matching element only
$q->html('<p>foo</p>');
```
### insert\_before
Insert every element in the set of matched elements before the target.
### insert\_after
Insert every element in the set of matched elements after the target.
### ` prepend `
Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
### remove
Delete the elements associated with the object from the DOM.
```
# remove all <blink> tags from the document
$q->find('blink')->remove;
```
### remove\_class
Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
### replace\_with
Replace the elements of the object with the provided replacement.
The replacement can be a string, a `Web::Query` object or an
anonymous function. The anonymous function is passed the index of the current
node and the node itself (with is also localized as `$_`).
```perl
my $q = wq( '<p><b>Abra</b><i>cada</i><u>bra</u></p>' );
$q->find('b')->replace_with('<a>Ocus</a>);
# <p><a>Ocus</a><i>cada</i><u>bra</u></p>
$q->find('u')->replace_with($q->find('b'));
# <p><i>cada</i><b>Abra</b></p>
$q->find('i')->replace_with(sub{
my $name = $_->text;
return "<$name></$name>";
});
# <p><b>Abra</b><cada></cada><u>bra</u></p>
```
### size
Return the number of elements in the Web::Query object.
```
wq('<div><p>foo</p><p>bar</p></div>')->find('p')->size; # 2
```
### text
Get/Set the text.
```perl
my @text = $q->text();
my $text = $q->text(); # 1st matching element only
$q->text('text');
```
If called in a scalar context, only return the string representation
of the first element
## OTHERS
- Web::Query->last\_response()
Returns last HTTP response status that generated by `new_from_url()`.
# HOW DO I CUSTOMIZE USER AGENT?
You can specify your own instance of [LWP::UserAgent](https://metacpan.org/pod/LWP%3A%3AUserAgent).
```perl
$Web::Query::UserAgent = LWP::UserAgent->new( agent => 'Mozilla/5.0' );
```
# FAQ AND TROUBLESHOOTING
## How to find XML processing instructions in a document?
It's possible with [Web::Query::LibXML](https://metacpan.org/pod/Web%3A%3AQuery%3A%3ALibXML) and by using an xpath expression
with `find()`:
```
# find <?xml-stylesheet ... ?>
$q->find(\"//processing-instruction('xml-stylesheet')");
```
However, note that the support for processing instructions
in [HTML::TreeBuilder::LibXML::Node](https://metacpan.org/pod/HTML%3A%3ATreeBuilder%3A%3ALibXML%3A%3ANode) is sketchy, so there
are methods like `attr()` that won't work.
## Can't get the content of script elements
The <script> tag is treated differently by [HTML::TreeBuilder](https://metacpan.org/pod/HTML%3A%3ATreeBuilder), the
parser used by Web::Query. To retrieve the content, you can use either
the method `html()` (with the caveat that the content will be escaped),
or use [Web::Query::LibXML](https://metacpan.org/pod/Web%3A%3AQuery%3A%3ALibXML), which parse the 'script' element differently.
```perl
my $node = "<script>var x = '<p>foo</p>';</script>";
say Web::Query::wq( $node )->text;
# nothing is printed!
say Web::Query::wq( $node )->html;
# var x = '<p>foo</p>';
say Web::Query::LibXML::wq( $node )->text;
# var x = '<p>foo</p>';
say Web::Query::LibXML::wq( $node )->html;
# var x = '<p>foo</p>';
```
# INCOMPATIBLE CHANGES
- 0.10
new\_from\_url() is no longer throws exception on bad response from HTTP server.
# AUTHOR
Tokuhiro Matsuno <tokuhirom AAJKLFJEF@ GMAIL COM>
# SEE ALSO
- [pQuery](https://metacpan.org/pod/pQuery)
- [XML::LibXML::jQuery](https://metacpan.org/pod/XML%3A%3ALibXML%3A%3AjQuery)
# LICENSE
Copyright (C) Tokuhiro Matsuno
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
# BUGS
Please report any bugs or feature requests on the bugtracker website
[https://github.com/tokuhirom/Web-Query/issues](https://github.com/tokuhirom/Web-Query/issues)
When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.
|