README.mkdn 19 KB

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