README 19 KB

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