Scrappy.pm.bak 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. # ABSTRACT: The All Powerful Web Spidering, Scraping, Creeping Crawling Framework
  2. # Dist::Zilla: +PodWeaver
  3. package Scrappy;
  4. BEGIN {
  5. $Scrappy::VERSION = '0.94112090';
  6. }
  7. # load OO System
  8. use Moose;
  9. # load other libraries
  10. use Carp;
  11. extends 'Scrappy::Scraper';
  12. sub crawl {
  13. my ($self, $starting_url, %pages) = @_;
  14. croak(
  15. 'Please provide a starting URL and a valid configuration before crawling'
  16. ) unless ($self && $starting_url && keys %pages);
  17. # register the starting url
  18. $self->queue->add($starting_url);
  19. # start the crawl loop
  20. while (my $url = $self->queue->next) {
  21. # check if the url matches against any registered pages
  22. foreach my $page (keys %pages) {
  23. my $data = $self->page_match($page, $url);
  24. if ($data) {
  25. # found a page match, fetch and scrape the page for data
  26. if ($self->get($url)->page_loaded) {
  27. foreach my $selector (keys(%{$pages{$page}})) {
  28. # loop through resultset
  29. foreach my $item (@{$self->select($selector)->data}) {
  30. # execute selector code
  31. $pages{$page}->{$selector}->($self, $item, $data);
  32. }
  33. }
  34. }
  35. }
  36. }
  37. }
  38. return $self;
  39. }
  40. 1;
  41. __END__
  42. =pod
  43. =head1 NAME
  44. Scrappy - The All Powerful Web Spidering, Scraping, Creeping Crawling Framework
  45. =head1 VERSION
  46. version 0.94112090
  47. =head1 SYNOPSIS
  48. #!/usr/bin/perl
  49. use Scrappy;
  50. my $scraper = Scrappy->new;
  51. $scraper->crawl('http://search.cpan.org/recent',
  52. '/recent' => {
  53. '#cpansearch li a' => sub {
  54. print $_[1]->{href}, "\n";
  55. }
  56. }
  57. );
  58. And now manually, ... without crawl, the above is similar to the following ...
  59. #!/usr/bin/perl
  60. use Scrappy;
  61. my $scraper = Scrappy->new;
  62. if ($scraper->get($url)->page_loaded) {
  63. $scraper->select('#cpansearch li a')->each(sub{
  64. print shift->{href}, "\n";
  65. });
  66. }
  67. =head1 DESCRIPTION
  68. Scrappy is an easy (and hopefully fun) way of scraping, spidering, and/or
  69. harvesting information from web pages, web services, and more. Scrappy is a
  70. feature rich, flexible, intelligent web automation tool.
  71. Scrappy (pronounced Scrap+Pee) == 'Scraper Happy' or 'Happy Scraper'; If you
  72. like you may call it Scrapy (pronounced Scrape+Pee) although Python has a web
  73. scraping framework by that name and this module is not a port of that one.
  74. =head2 FEATURES
  75. Scrappy provides a framework containing all the tools neccessary to create a
  76. simple yet powerful web scraper. At its core, Scrappy loads an array of
  77. features for access control, event logging, session handling, url matching,
  78. web request and response handling, proxy management, web scraping, and downloading.
  79. Futhermore, Scrappy provides a simple Moose-based plugin system that allows Scrappy
  80. to be easily extended.
  81. my $scraper = Scrappy->new;
  82. $scraper->control; # Scrappy::Scraper::Control (access control)
  83. $scraper->parser; # Scrappy::Scraper::Parser (web scraper)
  84. $scraper->user_agent; # Scrappy::Scraper::UserAgent (user-agent tools)
  85. $scraper->logger; # Scrappy::Logger (event logger)
  86. $scraper->queue; # Scrappy::Queue (flow control for loops)
  87. $scraper->session; # Scrappy::Session (session management)
  88. Please see the METHODS section for a more in-depth look at all Scrappy
  89. functionality.
  90. =head2 ATTRIBUTES
  91. The following is a list of object attributes available with every Scrappy instance,
  92. attributes always return an instance of the class they represent.
  93. =head3 content
  94. The content attribute holds the L<HTTP::Response> object of the current request.
  95. Returns undef if no page has been successfully fetched.
  96. my $scraper = Scrappy->new;
  97. $scraper->content;
  98. =head3 control
  99. The control attribute holds the L<Scrappy::Scraper::Control> object which is used
  100. the provide access conrtol to the scraper.
  101. my $scraper = Scrappy->new;
  102. $scraper->control;
  103. ... $scraper->control->restrict('google.com');
  104. ... $scraper->control->allow('cpan.org');
  105. ... if $scraper->control->is_allowed($url);
  106. =head3 debug
  107. The debug attribute holds a boolean which controls whether event logs are captured.
  108. my $scraper = Scrappy->new;
  109. $scraper->debug(1);
  110. =head3 logger
  111. The logger attribute holds the L<Scrappy::Logger> object which is used to provide
  112. event logging capabilities to the scraper.
  113. my $scraper = Scrappy->new;
  114. $scraper->logger;
  115. =head3 parser
  116. The parser attribute holds the L<Scrappy::Scraper::Parser> object which is used
  117. to scrape html data from the specified source material.
  118. my $scraper = Scrappy->new;
  119. $scraper->parser;
  120. =head3 plugins
  121. The plugins attribute holds the L<Scrappy::Plugin> object which is an interface
  122. used to load plugins.
  123. my $scraper = Scrappy->new;
  124. $scraper->plugins;
  125. =head3 queue
  126. The queue attribute holds the L<Scrappy::Queue> object which is used to provide
  127. flow-control for the standard loop approach to crawling.
  128. my $scraper = Scrappy->new;
  129. $scraper->queue;
  130. =head3 session
  131. The session attribute holds the L<Scrappy::Session> object which is used to provide
  132. session support and persistent data across executions.
  133. my $scraper = Scrappy->new;
  134. $scraper->session;
  135. =head3 user_agent
  136. The user_agent attribute holds the L<Scrappy::Scraper::UserAgent> object which is
  137. used to set and manipulate the user-agent header of the scraper.
  138. my $scraper = Scrappy->new;
  139. $scraper->user_agent;
  140. =head3 worker
  141. The worker attribute holds the L<WWW::Mechanize> object which is used navigate web
  142. pages and provide request and response header information.
  143. my $scraper = Scrappy->new;
  144. $scraper->worker;
  145. =head1 METHODS
  146. =head2 back
  147. The back method is the equivalent of hitting the "back" button in a browser, it
  148. returns the previous page (response) and returns that URL, it will not backtrack
  149. beyond the first request.
  150. my $scraper = Scrappy->new;
  151. $scraper->get(...);
  152. ...
  153. $scraper->get(...);
  154. ...
  155. my $last_url = $scraper->back;
  156. =head2 cookies
  157. The cookies method returns an HTTP::Cookie object. Note! Cookies can be made
  158. persistent by enabling session-support. Session-support is enable by simply
  159. specifying a file to be used.
  160. my $scraper = Scrappy->new;
  161. $scraper->session->write('session.yml'); # enable session support
  162. $scraper->get(...);
  163. my $cookies = $scraper->cookies;
  164. =head2 crawl
  165. The crawl method is very useful when it is desired to crawl an entire website or
  166. at-least partially, it automates the tasks of creating a queue, fetching and
  167. parsing html pages, and establishing simple flow-control. See the SYNOPSIS for
  168. a simplified example, ... the following is a more complex example.
  169. my $scrappy = Scrappy->new;
  170. $scrappy->crawl('http://search.cpan.org/recent',
  171. '/recent' => {
  172. '#cpansearch li a' => sub {
  173. my ($self, $item) = @_;
  174. # follow all recent modules from search.cpan.org
  175. $self->queue->add($item->{href});
  176. }
  177. },
  178. '/~:author/:name-:version/' => {
  179. 'body' => sub {
  180. my ($self, $item, $args) = @_;
  181. my $reviews = $self
  182. ->select('.box table tr')->focus(3)->select('td.cell small a')
  183. ->data->[0]->{text};
  184. $reviews = $reviews =~ /\d+ Reviews/ ?
  185. $reviews : '0 reviews';
  186. print "found $args->{name} version $args->{version} ".
  187. "[$reviews] by $args->{author}\n";
  188. }
  189. }
  190. );
  191. =head2 domain
  192. The domain method returns the domain host of the current page. Local pages, e.g.
  193. file:///this/that/the_other will return undef.
  194. my $scraper = Scrappy->new;
  195. $scraper->get('http://www.google.com');
  196. print $scraper->domain; # print www.google.com
  197. =head2 download
  198. The download method is passed a URL, a Download Directory Path and a optionally
  199. a File Path, then it will follow the link and store the response contents into
  200. the specified file without leaving the current page. Basically it downloads the
  201. contents of the request (especially when the request pushes a file download). If
  202. a File Path is not specified, Scrappy will attempt to name the file automatically
  203. resorting to a random 6-charater string only if all else fails, then returns to
  204. the originating page.
  205. my $scaper = Scrappy->new;
  206. my $requested_url = '...';
  207. $scraper->download($requested_url, '/tmp');
  208. # supply your own file name
  209. $scraper->download($requested_url, '/tmp', 'somefile.txt');
  210. =head2 dumper
  211. The dumper method is a convenience feature that passes the passed-in objects to
  212. L<Data::Dumper> which in turn returns a stringified representation of that
  213. object/data-structure.
  214. my $scaper = Scrappy->new;
  215. my $requested_url = '...';
  216. $scraper->get($requested_url);
  217. my $data = $scraper->select('//a[@href]')->data;
  218. # print out the scraped data
  219. print $scraper->dumper($data);
  220. =head2 form
  221. The form method is used to submit a form on the current page.
  222. my $scraper = Scrappy->new;
  223. $scraper->form(fields => {
  224. username => 'mrmagoo',
  225. password => 'foobarbaz'
  226. });
  227. # or more specifically, for pages with multiple forms
  228. $scraper->form(form_name => 'login_form', fields => {
  229. username => 'mrmagoo',
  230. password => 'foobarbaz'
  231. });
  232. $scraper->form(form_number => 1, fields => {
  233. username => 'mrmagoo',
  234. password => 'foobarbaz'
  235. });
  236. =head2 get
  237. The get method takes a URL or URI object, fetches a web page and returns the
  238. Scrappy object.
  239. my $scraper = Scrappy->new;
  240. if ($scraper->get($new_url)->page_loaded) {
  241. ...
  242. }
  243. # $self->content has the HTTP::Response object
  244. =head2 log
  245. The log method logs an event with the event logger.
  246. my $scraper = Scrappy->new;
  247. $scraper->debug(1); # unneccessary, on by default
  248. $scraper->logger->verbose(1); # more detailed log
  249. $scraper->log('error', 'Somthing bad happened');
  250. ...
  251. $scraper->log('info', 'Somthing happened');
  252. $scraper->log('warn', 'Somthing strange happened');
  253. $scraper->log('coolness', 'Somthing cool happened');
  254. Note! Event logs are always recorded but never automatically written to a file
  255. unless explicitly told to do so using the following:
  256. $scraper->logger->write('log.yml');
  257. =head2 page_content_type
  258. The page_content_type method returns the content_type of the current page.
  259. my $scraper = Scrappy->new;
  260. $scraper->get('http://www.google.com/');
  261. print $scraper->page_content_type; # prints text/html
  262. =head2 page_data
  263. The page_data method returns the HTML content of the current page, additionally
  264. this method when passed a string with HTML markup, updates the content of the
  265. current page with that data and returns the modified content.
  266. my $scraper = Scrappy->new;
  267. $scraper->get(...);
  268. my $html = $scraper->page_data;
  269. =head2 page_ishtml
  270. The page_ishtml method returns true/false based on whether our content is HTML,
  271. according to the HTTP headers.
  272. my $scraper = Scrappy->new;
  273. $scraper->get($requested_url);
  274. if ($scraper->is_html) {
  275. ...
  276. }
  277. =head2 page_loaded
  278. The page_loaded method returns true/false based on whether the last request was
  279. successful.
  280. my $scraper = Scrappy->new;
  281. $scraper->get($requested_url);
  282. if ($scraper->page_loaded) {
  283. ...
  284. }
  285. =head2 page_match
  286. The page_match method checks the passed-in URL (or URL of the current page if
  287. left empty) against the URL pattern (route) defined. If URL is a match, it will
  288. return the parameters of that match much in the same way a modern web application
  289. framework processes URL routes.
  290. my $url = 'http://somesite.com/tags/awesomeness';
  291. ...
  292. my $scraper = Scrappy->new;
  293. # match against the current page
  294. my $this = $scraper->page_match('/tags/:tag');
  295. if ($this) {
  296. print $this->{'tag'};
  297. # ... prints awesomeness
  298. }
  299. .. or ..
  300. # match against a passed url
  301. my $this = $scraper->page_match('/tags/:tag', $url, {
  302. host => 'somesite.com'
  303. });
  304. if ($this) {
  305. print "This is the ", $this->{tag}, " page";
  306. # ... prints this is the awesomeness page
  307. }
  308. =head2 page_reload
  309. The page_reload method acts like the refresh button in a browser, it simply
  310. repeats the current request.
  311. my $scraper = Scrappy->new;
  312. $scraper->get(...);
  313. ...
  314. $scraper->reload;
  315. =head2 page_status
  316. The page_status method returns the 3-digit HTTP status code of the response.
  317. my $scraper = Scrappy->new;
  318. $scraper->get(...);
  319. if ($scraper->page_status == 200) {
  320. ...
  321. }
  322. =head2 page_text
  323. The page_text method returns a text representation of the last page having
  324. all HTML markup stripped.
  325. my $scraper = Scrappy->new;
  326. $scraper->get(...);
  327. my $text = $scraper->page_text;
  328. =head2 page_title
  329. The page_title method returns the content of the title tag if the current page
  330. is HTML, otherwise returns undef.
  331. my $scraper = Scrappy->new;
  332. $scraper->get('http://www.google.com/');
  333. my $title = $scraper->page_title;
  334. print $title; # print Google
  335. =head2 pause
  336. This method sets breaks between your requests in an attempt to simulate human
  337. interaction.
  338. my $scraper = Scrappy->new;
  339. $scraper->pause(20);
  340. $scraper->get($request_1);
  341. $scraper->get($request_2);
  342. $scraper->get($request_3);
  343. Given the above example, there will be a 20 sencond break between each request made,
  344. get, post, request, etc., You can also specify a range to have the pause method
  345. select from at random...
  346. $scraper->pause(5,20);
  347. $scraper->get($request_1);
  348. $scraper->get($request_2);
  349. # reset/turn it off
  350. $scraper->pause(0);
  351. print "I slept for ", ($scraper->pause), " seconds";
  352. Note! The download method is exempt from any automatic pausing.
  353. =head2 plugin
  354. The plugin method allow you to load a plugin. Using the appropriate case is
  355. recommended but not neccessary. See L<Scrappy::Plugin> for more information.
  356. my $scraper = Scrappy->new;
  357. $scraper->plugin('foo_bar'); # will load Scrappy::Plugin::FooBar
  358. $scraper->plugin('foo-bar'); # will load Scrappy::Plugin::Foo::Bar
  359. $scraper->plugin('Foo::Bar'); # will load Scrappy::Plugin::Foo::Bar
  360. # more pratically
  361. $scraper->plugin('whois', 'spammer_check');
  362. ... somewhere in code
  363. my $var = $scraper->plugin_method();
  364. # example using core plugin Scrappy::Plugin::RandomProxy
  365. my $s = Scrappy->new;
  366. $s->plugin('random_proxy');
  367. $s->use_random_proxy;
  368. $s->get(...);
  369. =head2 post
  370. The post method takes a URL, a hashref of key/value pairs, and optionally an
  371. array of key/value pairs, and posts that data to the specified URL, then returns
  372. an HTTP::Response object.
  373. my $scraper = Scrappy->new;
  374. $scraper->post($requested_url, {
  375. input_a => 'value_a',
  376. input_b => 'value_b'
  377. });
  378. # w/additional headers
  379. my %headers = ('Content-Type' => 'multipart/form-data');
  380. $scraper->post($requested_url, {
  381. input_a => 'value_a',
  382. input_b => 'value_b'
  383. }, %headers);
  384. Note! The most common post headers for content-type are
  385. application/x-www-form-urlencoded and multipart/form-data.
  386. =head2 proxy
  387. The proxy method will set the proxy for the next request to be tunneled through.
  388. my $scraper = Scrappy->new;
  389. $scraper->proxy('http', 'http://proxy1.example.com:8000/');
  390. $scraper->get($requested_url);
  391. $scraper->proxy('http', 'ftp', 'http://proxy2.example.com:8000/');
  392. $scraper->get($requested_url);
  393. # best practice when using proxies
  394. use Tiny::Try;
  395. my $proxie = Scrappy->new;
  396. $proxie->proxy('http', 'http://proxy.example.com:8000/');
  397. try {
  398. $proxie->get($requested_url);
  399. } catch {
  400. die "Proxy failed\n";
  401. };
  402. Note! When using a proxy to perform requests, be aware that if they fail your
  403. program will die unless you wrap your code in an eval statement or use a try/catch
  404. mechanism. In the example above we use Tiny::Try to trap any errors that might occur
  405. when using proxy.
  406. =head2 request_denied
  407. The request_denied method is a simple shortcut to determine if the page you
  408. requested got loaded or redirected. This method is very useful on systems
  409. that require authentication and redirect if not authorized. This function
  410. return boolean, 1 if the current page doesn't match the requested page.
  411. my $scraper = Scrappy->new;
  412. $scraper->get($url_to_dashboard);
  413. if ($scraper->request_denied) {
  414. # do login, again
  415. }
  416. else {
  417. # resume ...
  418. }
  419. =head2 response
  420. The response method returns the HTTP::Repsonse object of the current page.
  421. my $scraper = Scrappy->new;
  422. $scraper->get(...);
  423. my $res = $scraper->response;
  424. =head2 select
  425. The select method takes XPATH or CSS selectors and returns a
  426. L<Scrappy::Scraper::Parser> object which contains the matching elements.
  427. my $scraper = Scrappy->new;
  428. # return a list of links
  429. my $list = $scraper->select('#profile li a')->data; # see Scrappy::Scraper::Parser
  430. foreach my $link (@{$list}) {
  431. print $link->{href}, "\n";
  432. }
  433. # Zoom in on specific chunks of html code using the following ...
  434. my $list = $scraper
  435. ->select('#container table tr') # select all rows
  436. ->focus(4) # focus on the 5th row
  437. ->select('div div')->data;
  438. # The code above selects the div > div inside of the 5th tr in #container table
  439. # Access attributes html, text and other attributes as follows...
  440. $element = $scraper->select('table')->data->[0];
  441. $element->{html}; # HTML representation of the table
  442. $element->{text}; # Table stripped of all HTML
  443. $element->{cellpadding}; # cellpadding
  444. $element->{height}; # ...
  445. =head2 stash
  446. The stash method sets a stash (shared) variable or returns a reference to the entire
  447. stash object.
  448. my $scraper = Scrappy->new;
  449. $scraper->stash(age => 31);
  450. print 'stash access works'
  451. if $scraper->stash('age') == $scraper->stash->{age};
  452. my @array = (1..20);
  453. $scraper->stash(integers => [@array]);
  454. =head2 store
  455. The store method stores the contents of the current page into the specified file.
  456. If the content-type does not begin with 'text', the content is saved as binary data.
  457. my $scraper = Scrappy->new;
  458. $scraper->get($requested_url);
  459. $scraper->store('/tmp/foo.html');
  460. =head2 url
  461. The url method returns the complete URL for the current page.
  462. my $scraper = Scrappy->new;
  463. $scraper->get('http://www.google.com/');
  464. print $scraper->url; # prints http://www.google.com/
  465. =head1 AUTHOR
  466. Al Newkirk <awncorp@cpan.org>
  467. =head1 COPYRIGHT AND LICENSE
  468. This software is copyright (c) 2010 by awncorp.
  469. This is free software; you can redistribute it and/or modify it under
  470. the same terms as the Perl 5 programming language system itself.
  471. =cut