Get Getting Started with PhantomJS Beltran Aries free all chapters
Get Getting Started with PhantomJS Beltran Aries free all chapters
com
https://textbookfull.com/product/getting-started-with-
phantomjs-beltran-aries/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/getting-started-with-kubernetes-2nd-
edition-baier/
textboxfull.com
https://textbookfull.com/product/make-getting-started-with-processing-
py-allison-parrish/
textboxfull.com
https://textbookfull.com/product/getting-started-with-gulp-second-
edition-travis-maynard/
textboxfull.com
https://textbookfull.com/product/getting-started-with-eeg-
neurofeedback-john-n-demos/
textboxfull.com
Getting Started With Angular 2nd Edition Stephen Adams
https://textbookfull.com/product/getting-started-with-angular-2nd-
edition-stephen-adams/
textboxfull.com
https://textbookfull.com/product/getting-started-with-microsoft-
system-center-operations-manager-kevin-greene/
textboxfull.com
https://textbookfull.com/product/getting-started-with-advanced-c-1st-
edition-vaskaran-sarcar-sarcar/
textboxfull.com
https://textbookfull.com/product/getting-started-with-natural-
language-processing-meap-v06-ekaterina-kochmar/
textboxfull.com
https://textbookfull.com/product/programming-with-stm32-getting-
started-with-the-nucleo-board-and-c-c-donald-norris/
textboxfull.com
Getting Started with
PhantomJS
Aries Beltran
BIRMINGHAM - MUMBAI
Getting Started with PhantomJS
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
ISBN 978-1-78216-422-7
www.packtpub.com
Reviewers Proofreader
Phil Sales Lauren Harkins
Stéphane Wirtel
Indexer
Acquisition Editors Tejal Soni
Owen Roberts
Martin Bell Production Coordinator
Nitesh Thakur
Commissioning Editor
Sruthi Kutty Cover Work
Nitesh Thakur
Technical Editors
Menza Mathew
Amit Shetty
Copy Editors
Sarang Chari
Tanvi Gaitonde
Insiya Morbiwala
Alfida Paiva
Lavina Pereira
About the Author
Phil Sales is a software development manager and has worked in this role for
more than 10 years. He started and managed development and testing teams for
various companies, mostly in the banking sector. Most of his projects have been
web application oriented, with a Java/J2EE flavor. His latest endeavor involved
starting up a Manila office for a UK-based software vendor, with development,
testing, and support teams. Based in Manila, he has also worked on projects in
the US, the UK, and Thailand.
Stéphane Wirtel has been one of the main developers of the OpenERP project for
the past six years. He is also a consultant for the high availability of OpenERP and
for the SaaS architecture of OpenERP. He has been an enthusiastic developer and
user of Linux for the past 15 years and has been working on Python for 10 years.
He likes to discover new technologies (LLVM, Erlang, Golang, and so on).
Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up
for a range of free newsletters and receive exclusive discounts and offers on Packt books
and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print and bookmark content
• On demand and accessible via web browser
[ ii ]
Table of Contents
Chapter 8: Cookies 89
Reading cookies 89
Baking some cookies 91
Deleting cookies 93
Keeping cookies 93
Summary 93
Chapter 9: External JavaScript 95
Modules 95
Using the object-oriented modules 98
Using third-party JavaScript libraries 100
Summary 101
Chapter 10: Testing with PhantomJS 103
What is unit testing? 103
Unit testing with Jasmine 103
Downloading Jasmine 105
Test specs with Jasmine 105
The PhantomJS Jasmine runner 111
Summary 116
Chapter 11: Maximizing PhantomJS 117
CasperJS 117
GhostDriver 120
Screenshots, web metrics, and more 120
Summary 121
Index 123
[ iii ]
Preface
PhantomJS is a fully scriptable headless browser. When I started using it two years
ago, I thought it was just another environment that can perform and evaluate
JavaScript, but, as I explored its features, to my surprise, I found it to be an awesome
technology. Most of the features that are discussed in this book come from the
bits and pieces of the application that I have been using in my work to create a
web monitoring and user-simulation type of service. PhantomJS is one of those
technologies that can be integrated into any existing platform and can solve web
development puzzles, ranging from page manipulation to user event simulation.
This book is a guide to help you not only ease your way into developing scripts in
PhantomJS but it will also show you the cool features of this technology. In addition,
it will also encourage you to be more creative and play with it as each chapter
unfolds new capabilities. This book will help you get started.
Chapter 2, Manipulating Page Content, shows you how to directly interact with pages
that we open in our headless browser.
Chapter 3, Handling Events and Callbacks, explores how to capture events that web
pages generate for the browser and reacts accordingly. We will also simulate browser
events that involve simulating the users' mouse and keyboard events.
Chapter 4, Capturing Errors, focuses on how to handle errors within PhantomJS and
those that are generated by the pages.
Chapter 5, Grabbing Pages, plays with one cool feature of PhantomJS, that is, capturing
screenshots programmatically.
Preface
Chapter 7, Working with Files, shows you how to work with files and understand
how these are supported by PhantomJS using its own FileSystem API.
Chapter 10, Testing with PhantomJS, focuses on the use of PhantomJS for testing.
We will learn how to use Jasmine, create test scripts, and make them work
using PhantomJS.
Chapter 11, Maximizing PhantomJS, goes over the different products that are written
using PhantomJS and shows how we can go beyond what we've learned from the
books to make our own applications.
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. The following are some examples of these styles,
and an explanation of their meaning.
[2]
Preface
Code words in text are shown as follows: "The onLoadStarted event will be
triggered when PhantomJS starts loading the page based on the resources received."
page.onLoadFinished = function () {
console.log('Page Loaded');
phantom.exit(0);
};
page.open(url);
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
[default]
exten => s,1,Dial(Zap/1|30)
exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
[3]
Preface
New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes, for example, appear in the text like this: "Using a
simple page open, handling these two events will give us two console prints: Page
Loading Started which is displayed first, followed by Page Loaded."
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.
[4]
Preface
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you would report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the errata submission form link,
and entering the details of your errata. Once your errata are verified, your submission
will be accepted and the errata will be uploaded on our website, or added to any list of
existing errata, under the Errata section of that title. Any existing errata can be viewed
by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.
We appreciate your help in protecting our authors, and our ability to bring
you valuable content.
Questions
You can contact us at [email protected] if you are having a problem
with any aspect of the book, and we will do our best to address it.
[5]
Getting Started
PhantomJS is a new solution that provides headless testing of web applications. It is
also a tool for dynamically capturing and rendering pages as images. It allows you to
programmatically manipulate page content to control and change it to different forms.
It can scrape websites and save important information to files. It will also provide you
network-level information of your page and site resources. These are just a few of the
functions that PhantomJS can do for us. It provides a fresh and a whole new way for
web designers, testers, and developers to perform and create browser-based solutions.
PhantomJS uses QtWebKit as its core browser capability and uses the WebKit
JavaScript engine for script interpretation and execution. Anything and everything
that you can do in a WebKit-based browser (such as Chrome, Safari, and Opera
browser) you can do with PhantomJS. It's more than just a browser because it
supports web standards, such as CSS selector, DOM manipulation, JSON, HTML5
Canvas, and SVG; moreover, you can do some cool stuff such as performing file
system I/O, accessing system environment variables, or even instantiating your
own implementation of a web server daemon.
Downloading PhantomJS
Before we go through the features of PhantomJS, first we need to get our copy of
the PhantomJS binaries. Typically, PhantomJS provides downloadable releases of
binaries that are precompiled and packaged. You can choose from Linux, Mac OS
X, and Windows precompiled packages. To download a copy, go to http://www.
phantomjs.org/download.html.
Getting Started
We will be using the Mac OS X version of PhantomJS throughout this book for
running code examples. Don't worry if you are working on a different platform;
the instructions are the same on all platforms.
Before you start downloading sources, you will need these tools installed on
your workspace:
[8]
Chapter 1
The PhantomJS team is always trying to find the optimal way to build the sources,
and the build instructions are frequently modified. To build PhantomJS properly,
you must follow the steps found here: http://phantomjs.org/build.html.
If you are not planning to hack into PhantomJS code and develop new features,
then it is best to download the pre-packaged binaries.
Open your terminal and then navigate to your PhantomJS bin folder. In the prompt,
execute phantomjs without any arguments.
[9]
Getting Started
Running PhantomJS without any arguments will give you an interactive prompt
that is similar to the JavaScript debug console you could find in any modern
browser. In this interactive prompt, we can execute JavaScript code line by line.
This functionality is very useful for debugging or testing code before you actually
build your script.
Say "Hello Ghost!" to PhantomJS using the interactive prompt. Using console.log
will output any type of data to the output console of a JavaScript interpreter.
phantomjs> console.log("Hello Ghost!")
Hello Ghost!
undefined
phantomjs>
See? It is simple. Just like coding any JavaScript. But wait. What is that undefined
message just after the Hello Ghost! message? That is not an error. It is just how the
interactive mode behaves. Each call is expected to return data just like any ordinary
function call and it also automatically outputs the data value to the output stream.
Since the console.log command does not return any value, the message is
undefined. If we issue an assignment to a variable command, the following output
will be displayed:
phantomjs> name = "Tara"
{}
phantomjs>
The assignment to a variable will take place and the result of the operation will be
displayed. Because it is in the form of a string literal, the undefined message will not
be displayed. The interactive mode is similar to a long-running script; any variable
or function you define will be loaded into the memory buffer and can be accessed
anytime during the session. So, based on our preceding example, the name variable
can also be displayed by referencing it.
phantomjs> name = "Tara"
"Tara"
phantomjs> name
"Tara"
phantomjs> name + " and Cecil"
"Tara and Cecil"
phantomjs>
[ 10 ]
Chapter 1
We can even use the variable with another operation as seen in the preceding lines
of code. However, any operation's result that is not assigned to a variable will be
available only during the execution of the line. The operation that concatenates the
name variable with another string literal will be performed, and the resulting string
will be displayed in the console but will not be kept in memory.
Objects can also be accessed within the interactive mode, and one of the most
commonly used objects is phantom. Try typing phantom in the prompt and you
will get the following output:
phantomjs> phantom
{
"clearCookies": "[Function]",
"deleteCookie": "[Function]",
"addCookie": "[Function]",
"injectJs": "[Function]",
"debugExit": "[Function]",
"exit": "[Function]",
"cookies": [],
"cookiesEnabled": true,
"version": {
"major": 1,
"minor": 7,
"patch": 0
},
"scriptName": "",
"outputEncoding": "UTF-8",
"libraryPath": "/Users/Aries/phantomjs/bin",
"defaultPageSettings": {
"XSSAuditingEnabled": false,
"javascriptCanCloseWindows": true,
"javascriptCanOpenWindows": true,
"javascriptEnabled": true,
"loadImages": true,
"localToRemoteUrlAccessEnabled": false,
[ 11 ]
Getting Started
PhantomJS displays the content of the object when used in the interactive prompt,
and even its own phantom object can be referenced. You may also observe that the
object is displayed in the form of JSON and details every attribute of the object
except for the function definition. Using this approach, we can also examine each
and every object, and we will be able to know what the exposed attributes and
available functions are.
Let's try using one of the most important functions available in the phantom
object: the exit() function. This function will enable us to quit PhantomJS and
return to the caller or to the underlying operating system.
phantomjs> phantom.exit()
$
This function signals the application to exit with a return code of zero or normal
and without errors. Passing a numeric value as an argument of the exit() function
denotes the error code to be passed back to the caller. This is helpful when trying
to write scripts that need to verify if the execution was successful or if an error
occurred and what type of error it was.
[ 12 ]
Chapter 1
In the preceding lines of code, right after calling phantomjs, we capture the error
code coming from the application using the $? function. We assign that to an OUT
variable and then perform a test on it in the succeeding lines. If the error is equal
to zero, then we display Done; otherwise, we say that the call failed.
$ ./trapme.sh
phantomjs> phantom.exit(0)
undefined
Done.
$ ./trapme.sh
phantomjs> phantom.exit(1)
undefined
Ooops! Failed.!
$
But, be warned. PhantomJS is a very active community, and every now and then,
changes are being introduced. New APIs and objects are being added, but of course,
there are few items that are being changed, and ultimately some of them become
deprecated or are totally removed. The PhantomJS website has a full list of all the
functions and syntax, and has proper tagging for deprecated functions. We should
visit it regularly to check for upcoming updates so that we can adjust appropriately
in our codes.
[ 13 ]
Getting Started
[ 14 ]
Chapter 1
This module is based on the open source Mongoose web server library that supports
multiple platforms, authorization, web sockets, URL rewrite, and even "resumeable"
downloads. For more information about Mongoose, visit http://code.google.
com/p/mongoose/.
The phantom object allows access to relevant data, such as cookies and library paths.
If we want to import or inject third-party JavaScript libraries, such as jQuery, we can
do that using the phantom object. We can also create a "catch all" event handler for
errors using the onError event of the phantom object.
PhantomJS not only allows us to harness the power of JavaScript but also gives us
a very useful API. Each day, more and more contributors are enhancing this API,
giving us more options and easier ways to solve real problems. We will learn more
about these APIs as we continue our journey learning about PhantomJS.
All of the arguments are optional. Using the command without arguments will bring
up the interactive mode.
[ 15 ]
Getting Started
The script filename may or may not end with a .js extension. PhantomJS supports
two types of scripting—JavaScript or CoffeeScript. We don't need to specify if the
script is in JavaScript or CoffeeScript; PhantomJS will automatically detect it. We will
be using JavaScript in our examples. If you want to learn more about CoffeeScript,
you may visit the CoffeeScript website at http://www.coffeescript.org.
We will create a simple script to load a site and then display the title of the page
when loaded successfully. Finally, we will exit. If the page fails to load, we will log
some message to the console.
var page = require('webpage').create();
page.open("http://www.packtpub.com", function(status) {
if ( status === "success" ) {
console.log(page.title);
[ 16 ]
Chapter 1
} else {
console.log("Page failed to load.");
}
phantom.exit(0);
});
The preceding PhantomJS script is very simple. First, we import the webpage
module, create an instance of the webpage object, and assign it to a variable
named page.
The page variable now holds an instance of the webpage module where an open
function is available. Next, we instructed PhantomJS through the webpage instance
to open and load the URL. The second parameter of the open function is a function
callback definition that will be executed upon completion of the opening of the
URL. Inside the definition, we check if the status is "success", and if it is, the page is
loaded, and then we will display the title of the page. Then, we call the exit function
to terminate the script. Let's save this code snippet as helloweb.js and execute it by
passing the filename as our first argument to the phantomjs binary.
Summary
At this point, we have learned quite a few basics of PhantomJS, but this is just the tip
of the coolness of the technology. We now know how to get started with PhantomJS,
and create small scripts to play around with it. We won't stop here. We will now
move on to the more interesting stuff that it can offer, such as manipulating web
pages, simulating user events, and grabbing screenshots. So, let's do more PhantomJS
coding in the succeeding chapters.
[ 17 ]
Random documents with unrelated
content Scribd suggests to you:
si el gobierno hubiera atropellado las leyes para castigar los
atropellos de otros, debería haber empezado por embarcarse él
para Canarias, y decir: Marchemos todos francamente, y yo el
primero, por la senda de presidio? Vaya, Andrés, que eso ni
suponerse puede, y si te cuentan que tal caso ha sucedido, puedes
decir que el que lo cuente es un malévolo de ésos que traen la
anarquía en el bolsillo. Diría el gobierno y diría bien: «Yo no hice tal
cosa, y si la hiciera, ¿qué diferencia habría entre los atentados del
pueblo y los míos? Porque en fin, mientras que la ley no le ha
declarado reo, el condenado es asesinado: en ese caso no habría
entre mi atentado y el del pueblo más que una diferencia, á saber:
que el pueblo asesinó malamente carlistas y yo asesino malamente
liberales».
Asesinatos por asesinatos, ya que los ha de haber, estoy por los del
pueblo.
Puedes estar seguro de que hay causa; y si no se les ha formado,
es porque andamos de prisa, ó por mejor decir, lo que ha ido á
Canarias no ha sido una cadena de culpables, sino una comisión
artística compuesta de liberales, que van á costa del gobierno á
acabar de descubrir aquellas islas, y escribir una memoria de las
alturas del globo, y á dar testimonio al mundo sobre todo de la altura
á que estamos, tomando el meridiano del pico de Tenerife.
También te habrán contado posteriormente otra pequeña
arbitrariedad ejecutada oficialmente en una vieja, en virtud de un
cúmplase de un héroe. ¡Dios nos libre de caer en manos de héroes!
Sólo te diré que á lo menos en Barcelona tuvieron que acometer una
fortaleza y exponerse á ser rechazados. Bueno es remontarse á las
causas de las cosas, al tronco, y no á las ramas. Es así que la
primera causa de que existen facciosos fueron las madres que los
parieron; ergo quitando de en medio á las madres; lo que queda.
Los teólogos dicen: sublata causa tollitur efectus. Es lástima que no
haya vivido el abuelo, porque mientras más arriba más seguro es el
golpe. Pero hemos tenido que contentarnos con la madre. Está
probado que así como Sansón tenía la fuerza en el pelo, los
facciosos tienen el veneno en la madre, que viene á ser la hiel de
ellos; en quitándosela se vuelven como malvas: así lo ha probado la
experiencia, porque de resultas el otro no ha fusilado más que á
treinta. ¿Quién sabe los que hubiera fusilado si hubiera tenido
madre todavía? Luego, las mujeres son las que están impidiendo la
felicidad de España, y hasta que no acabemos con ellas no hay que
pensar en tener tranquilidad. En cuanto á las hermanas, como
estaban casadas con guardias nacionales, les tocaba fusilar la mitad
á los de allá, y la otra mitad á los de acá; pero nosotros, más
desprendidos, no quisimos perdonar ni la mitad que nos tocaba, y lo
fusilamos todo. ¡Bienaventurados en tiempos de héroes los
incluseros, porque ellos no tienen padre ni madre que les fusilen!
Pasadas estas etiquetas de recíproca cortesía, dieron en correr
voces de que el ejército estaba descontento, y que la guerra de
Navarra no iba lo ligera que debía. Felizmente para todos, algunos
amigos tuyos y míos, que así saben mover la pluma como esgrimir
la espada, enderezaron la opinión en artículos luminosos, probando
lo que ninguno debía tener olvidado, que las guerras civiles son
largas, á pesar de todos los programas del mundo; que éstos son
por el contrario los que tienen corta vida; que así las civiles como las
demás se sostienen con dinero y con soldados; que un gobierno en
lucha con una facción pierde más cuando pierde una batalla, que
adelanta cuando la gana, y que una derrota nuestra nos quita más
honra que gloria da á la facción; que por lo tanto es fuerza no
aventurarse sino á ciencia cierta; que la guerra no se hace en el
ministerio, sino en Vizcaya; que de real orden se llevan y se traen
jueces, se envían buques á Canarias, y se conquistan votos, pero
de real orden no se ganan batallas; que algunos descalabros
nuestros han sido debidos á reales órdenes; que para hacer la
guerra se necesita un plan; que para tener plan es preciso que el
general sólo sea responsable; y que Córdoba, en fin, sin que haya
necesidad de llamarle héroe, tiene un plan, el cual es forzoso dejarle
llevar á cabo, siquiera porque no ha habido hasta ahora otro mejor
que el suyo.
Tales razones no convencieron, fué bien acogida la representación
del ejército, y si bien ninguno de los que hablaban fué á dar su brazo
en vez de su voto, al fin no se admitió la dimisión, y sigue el general,
y su plan, y la guerra de Navarra, en el mejor estado posible.
Mientras todo esto pasaba echáronse encima las próximas
elecciones, hoy ya pasadas, y porque digo se echaron encima, no
vayas á pensar alguna tontería. Dijeron muchos si habría amaños ó
si no habría amaños; que se escribió largo y se intrigó más. Lo
primero solo prueba cultura en el país, lo segundo arguye talento.
¡Vaya usted á impedir que hablen las gentes! Para que no fuesen
las elecciones muy populares bastante amaño era ya la propia ley
electoral, en virtud de la cual debían elegir los electores nombrados
por los ayuntamientos y los mayores contribuyentes. No hay cosa
para elegir como las muchas talegas: una talega difícilmente se
equivoca; dos talegas siempre aciertan, y muchas talegas juntas
hacen maravillas. Ellas han podido decir á su procurador por boca
de los mayores contribuyentes la famosa fórmula aragonesa: «Nos,
que cada una de nos valemos tanto como vos, y todas juntas mucho
más que vos, os hacemos procurador».
Luego, los elegidos habían de tener doce mil reales de renta: gran
garantía de acierto: por poco que valga un real en estos tiempos, no
hay real que no valga una idea, sin contar con las muchas que hasta
ahora hemos visto que no valían un real, y con los varios casos en
que por menos de real daría uno todas sus ideas: bueno es siempre
que haya reales en el Estamento por si acaso no hubiese ideas.
Tanto mejor si hay lo uno y lo otro.
No es menos importante lo de los treinta años; no es menos
simbólico ni cabalístico el número de treinta que el de tres tan
citado, y de que es décuplo; treinta días tiene el mes, treinta minutos
cada media hora, por treinta dineros vendió Judas á un Dios, treinta
años representa la vida de un jugador, y treinta años, en fin, la
capacidad de un procurador. Muchos filósofos han creído que
cuando el hombre nace, el Ser Supremo, que esta atisbando, le
sopla dentro el alma por medio del mismo procedimiento que usa un
operario en una fábrica de cristales para dar forma á una vasija;
pero eso es el alma, mas no la capacidad y la facultad de procurar:
esta tal otra quisicosa se la infunde el Criador el día que cumple
treinta años, por la mañanita temprano, así como la aptitud legal y la
mayoría se la comunica á los veinte y cinco. Oh tú, Andrés, que no
los has cumplido, está con cuidado el día que los hayas de cumplir,
y escríbeme para mi gobierno lo que sientas en ese día: dime por
dónde entra la capacidad, y hacia dónde se coloca en tu persona:
prevenido de esa suerte de los síntomas que la anuncian podré yo
hacer á la mía, el día que me baje, el recibimiento que se debe á tan
ilustre huésped. ¿Cuándo tendremos treinta años? Aquel día
seremos ya unos hombrecitos.
Bien ha habido hombres que han discurrido antes de los treinta
años, pero ésos son fenómenos portentosos, raros ejemplos de no
vista precocidad; y en cuanto á Pitt y otros de su especie, ministros
ya mucho antes, ni siquiera es posible considerarlos como
monstruos de naturaleza; es fuerza inferir error de cálculo y mala fe
en la de bautismo.
El haber nacido en la provincia, ó tener en ella arraigo, no es de
menos importancia, si recordamos que las primeras impresiones se
graban para siempre en la cabeza del niño, y deciden de lo que ha
de ser después cuando grande: ni es posible que un hombre
conozca su provincia, y se interese por ella, si no ha nacido por allí
cerca. Puede suceder que una provincia tenga más confianza en la
reputación, en el saber de un forastero; pero páselo en paciencia la
buena de la provincia, que más pasó Cristo por ella.
Dicen sin embargo que todos los electores no han tenido presentes
todas esas verdades; así que, unos procuradores no han nacido,
otros no tienen la renta, ¡qué sé yo! Esto tiene compostura habiendo
comisión de poderes, y en todo caso se aplica la renta de unos á
otros, como hacen los buenos cristianos con los méritos de nuestro
Señor Jesucristo, que valen mucho más que las rentas; y así
poniendo de aquí y quitando de allí tengo para mí que se ha de
remediar. Y aun yo diría más. Don Juan Álvarez Mendizábal fué
elegido por ejemplo por Barcelona, siendo natural de Cádiz, y no
habiendo residido en Cataluña. Decían: «Pero no tiene nada suyo
en Cataluña, sino los electores:» ¿pues eso no es tener?, ¿no valen
tanto por lo menos los electores como una casa, ó una tapia, ó unas
cuantas fanegas de pan llevar? ¡Sino que poniéndose á hablar las
gentes!...
Por lo demás es sabido que el gobierno no ha influido
absolutamente nada en las elecciones, y desde luego se dijo que
eran á pedir de boca. Para que formes una idea, han salido elegidos
los sugestos siguientes:
Por Barcelona, como llevo dicho, don Juan Álvarez Mendizábal.
Por Cádiz, don Juan Álvarez Mendizábal.
Por Gerona, don Juan Álvarez Mendizábal.
Por Granada, don Juan Álvarez Mendizábal.
Por Madrid, don Juan Álvarez Mendizábal.
Por Málaga, don Juan Álvarez Mendizábal.
Por Pontevedra, don Juan Álvarez Mendizábal, etc., etc., etc.
Que es el cuento de pasó una cabra, y volvió y pasó otra, y volvió á
tornar y á pasar otra cabra, y así sucesivamente.
Si oyes decir que se abre el Estamento, di que es broma, que quien
se abre es don Juan Álvarez Mendizábal.
No habrás olvidado que los ministros de estado y de hacienda, y el
presidente del consejo, son don Juan Álvarez Mendizábal, y que los
otros ministros no son sino una manera de ser, distinta sólo en la
apariencia del don Juan Álvarez Mendizábal. Ahora figúrate el día
que el Estamento don Juan Álvarez Mendizábal pida cuentas al
ministro don Juan Álvarez Mendizábal...; aquí llaman esto un
gobierno representativo: sin que sea murmuración, confieso que yo
llamo esto un hombre representativo.
Una vez conocida la buena índole de las elecciones y la idoneidad
de esos diversos señores procuradores, ocurrió la duda de si estas
Cortes que iban á reunirse vendrían sólo para hacer una ley
electoral mejor que la que les confiere su derecho; ó si podrían
constituirse revisoras. Quiénes se agarraron á la legalidad, diciendo
que esto último sería ilegal; quiénes intentaron probar que lo de
menos era la legalidad, y que lo que importaba era la conveniencia.
Por fin salimos del atolladero, y parece que no tratarán de
constituirse por varias razones. Porque no han sido convocadas
para eso. Porque siendo su objeto principal hacer una ley electoral,
en virtud de la cual puedan convocarse luego las revisoras, es claro
que los demás asuntos que á ellas se sometan, por importantes que
sean, habrán de ser subalternos al principal. La nación tiene un
cimiento, y necesita una casa: en estas Cortes va á decidir cuáles
han de ser las circunstancias del arquitecto que se la puede hacer á
su gusto. Por consiguiente, todo lo que sea proceder á construir el
que sólo está comisionado para designar el constructor, es hacer la
casa y dejar para después el arquitecto: equivale á blanquear
después de pintar; es dejar al que venga detrás el derecho de poner
en duda la validez de la construcción.
En estas disputas andábamos, cuando otro run run más terrible vino
á poner nuevo espanto en nuestro corazón. He aquí que una noche
corre la voz de que se va á poner la constitución del año 12. ¡Bravo!,
dije yo: esto es lo que se llama andar camino. Aquí no se sabe
multiplicar, pero restar á las mil maravillas. Vamos á quién puede
más. El año 14 vino el rey y dijo: quien de catorce quita seis, queda
en ocho. Vuelvan pues las cosas al ser y estado del año 8. El año
20 vienen los otros y dicen: quien de veinte quita seis, queda en
catorce: vuelvan las cosas al ser y estado del año 14. El año 23
vuelve el de más arriba y dice: quien de veinte y tres quita tres,
queda en veinte; vuelvan las cosas al ser y estado de febrero del
año 20. El año 1836 asoman los segundos, y éstos quieren restar
más en grande: quien de treinta y seis quita veinte y cuatro, queda
en doce; vuelva todo al año 12. Éstos han pujado, si se exceptúa el
del Estatuto, que más picado que nadie cogió y lo restó todo, y nos
plantó en el siglo xv.
¡Diantre!, ¡si volveremos todavía á la venida de Túbal! Sepamos
primero cómo se entiende nuestro progreso. ¿Hacia dónde vamos?
¿Hacia atrás, ó hacia adelante? Tengamos el cuento del cochero,
que, montado al revés, arreaba al coche.
Ya te lo he dicho: tejedores; tejer y destejer. Nadie vende su tela, y
nadie hace tela nueva.
Decían ellos que el volver atrás no era más que tomar carrera. ¡Dios
los bendiga, y qué larga la toman!
Vamos claros. La constitución del año 12 era gran cosa en verdad,
pero para el año 12: en el día da la maldita casualidad de que
somos más liberales que entonces: si te he de hablar ingenuamente,
á mí me parece poco.
Las circunstancias del año 12, la guerra que sosteníamos apoyada
en el fanatismo popular, y el mayor atraso de la época, exigieron
concesiones en el día no necesarias, ridículas.
En ellas hablan las Cortes en nombre de Dios Todopoderoso, Padre,
Hijo y Espíritu Santo: gran principio para una novena: buena es la
devoción, pero á su tiempo: eso es adoptar, heredar de la
monarquía el derecho divino: la sociedad puede servir á Dios en
toda clase de gobiernos. El Supremo Hacedor no delega facultades
temporales ningunas, ni en un soberano, ni en un congreso; la
sociedad se hace ella misma por derecho propio sus reyes y sus
asambleas. Cristo vino al mundo á predicar, no á redactar códigos.
Á Dios daremos cuenta de nuestras creencias, no á los hombres:
reflexión igualmente aplicable al capítulo II, artículo 12, porque el
Salvador quiso convencer, no obligar, porque no quiere más
homenajes que los voluntarios.
Ítem más: en la constitución del año 12 no está consignada la
libertad de imprenta, sino para las ideas políticas, y eso es decirle á
un hombre: Ande usted, pero con una sola pierna.
En cambio nos impone como ley fundamental el amor á la patria y la
obligación de ser justos y benéficos... en cambio... Andrés mío,
callemos, porque, repito, que la venero, y tengo por indigno de un
liberal poner en ridículo el paladión de nuestra independencia
nacional, y la cuna de nuestra libertad, por fácil que eso sea. Pero la
respeto, como Cristo respetó el testamento viejo, fundando el nuevo.
Veneremos el viejo código, y venga no obstante otro nuevo más
adecuado á la época.
Parécense los hombres del año 12, amigo Andrés, al cura que no
sabía leer más que en su breviario: ó mejor al gastrónomo en Vista-
Alegre, que viendo su mesa puesta, pugna por sentarse á ella en
cuanto le dejan un momento libre, en cuanto ve un resquicio por
donde acercarse á la mesa. El caso es el mismo: todos les hacemos
cumplimientos, pero no les dejamos sentarse. Unas veces se lo
impidió el poseedor don Pascual de la Rivera, otras los mozos de su
fábrica... Convengo en que es una desesperación; pero culpen, no á
nosotros, sino á ellos mismos, que tantas veces se dejaron
interrumpir antes de llegar el bocado á la boca.
Aténgome á su artículo, que dice:
«La nación española es libre é independiente, y no es ni puede ser
patrimonio de ninguna familia, ni persona».
Esto digo yo: entre á gobernar, no éste ni aquél, sino todo el que se
sienta con fuerzas, todo el que dé pruebas de idoneidad. Basta de
ensayos. Á eso nos responden ellos: «¿Y dónde están esos
hombres?» ¿Dónde han de estar? En la calle, esperando á que
acaben de bailar los señores mayores, para entrar ellos en el baile.
«¿Cómo no salen esos hombres?», añaden. ¿Cómo han de salir?
De Calomarde acá, ¿qué protección, qué ley electoral ha llamado á
los hombres nuevos para darles entrada en la república? Cuenta sin
embargo con ella, y llámelos la ley presto: ¡¡¡déjese entrar
legalmente á los hombres del año 1836, ó se entrarán ellos de
rondón!!!
En conclusión, hombres nuevos para cosas nuevas: en tiempos
turbulentos hombres fuertes sobre todo, en quienes no esté cansada
la vida, en quienes haya ilusiones todavía, hombres que se paguen
de gloria, y en quien arda una noble ambición y arrojo constante
contra el peligro.
«¿Qué saben los jóvenes?», exclaman. Lo que ustedes nos han
enseñado, les responderemos, más lo que en ustedes hemos
escarmentado, más lo que seguimos aprendiendo. ¡Y qué eran
ustedes el año 12! Nosotros fundaremos nuestro orgullo en ser sus
sucesores, en aprovechar sus lecciones, en coronar la obra que
empezaron. Nosotros no rehusamos su mérito; no rehúsen ellos
nuestra idoneidad, que el árbol joven es la esperanza del jardinero,
si el viejo ya le da sombra.
Según el miedo que tienen de que la juventud entre en los puestos,
no parece sino que es posible hacerlo peor que ellos.
Para el año 1836 la única constitución posible es la constitución de
1836.
Una idea te diría, si no la hubieras de contar; y sólo á ti te la diría,
porque ellos la tomarán á personalidad, si de ella hiciese un artículo,
y sabe Dios que no lo digo por tal. Mucho venero á los hombres de
otra época, Andrés mío; mucho saben, sobre todo en no hablándose
de gobernar, para lo cual ya nos han manifestado repetidas veces
hasta donde rayan: mucho saben, y tanto que no sólo no los
lanzaría yo de la república, sino que los guardara muy guardados
como guardaban los romanos los libros sibilinos, para consultarlos
con el mayor respeto: de ellos armaría una biblioteca viva, donde
vueltos de espaldas en muy pulidos estantes, leyese el estudioso
encima Fulano, de Economía Política; Mengano, de Reformas
Constitucionales; Zutano, de la Guerra de la Independencia;
Perengano, de Metáforas y del Espíritu del Siglo, etc., etc.; de suerte
que no hubiese más que volverlos y ojearlos en un apuro, cuidando
mucho de quitarles antes y después el polvo, y de tornarlos á volver
hasta otra duda, como pergaminos preciosos.
Ahí verás tú si los respeto, y si los tengo en estima.
Hasta aquí de la constitución y de los hombres del año 12. Pasó el
susto, y la noticia, como habrás visto, no tuvo consecuencia. Sin
duda el ruido que metió fué el último cumplimiento de despedida que
nos hizo.
No ganamos para sustos. Posteriormente se cruzaron de palabras el
pueblo de Valencia y su capitán general. Éste tomó una porción de
providencias, entre otras las de Villadiego; con cuyo ingenioso
arbitrio no le pudieron haber los valencianos, que es decir que ha
podido más que ellos, que se ha burlado de ellos. Tiene mucho
talento. Buen chasco se han llevado. Así, así: á los alborotadores
hay que jugarles esas pasadas; con eso escarmientan. Á buen
seguro que si Basa hubiera hecho otro tanto, no le hubieran
deshecho á él, y el pueblo de Barcelona se hubiera llevado el mismo
chasco que el de Valencia. ¿No queréis capitán general? Pues
tomad capitán general. ¿No te figuras tú al pueblo de Valencia
buscando á su capitán general por todas partes, como quien busca
una sanguijuela extraviada, y él trota que trota para Madrid? Á mí
me hace morir de risa. Es lo que él dice: «¿Pues qué, querían
ustedes que me mataran?» ¿Qué habíamos de querer?
Conque ahora está aquí bueno, gordo y tranquilo; no ha sido poca
fortuna el poderlo contar.
En Zaragoza fué por otro estilo: salieron unos carlistas sentenciados
á qué sé yo qué bobería: se levantó el pueblo, sitió á los jueces, y
dieron en quererlos juzgar. Al maestro cuchillada. Pero no les da el
naipe para esos pasajes á los jueces de Zaragoza, como á los
capitanes generales de Valencia.
Entre tanto el ministerio de gracia y justicia sigue siempre de
mudanza, y hace bien, porque el juez que no da fruto en una tierra,
lo da en otra. El juez ha de ser como el zapato, hecho al pie; por eso
el que no le viene bien al uno, le viene al otro.
Para eso el de la gobernación no se mete con nadie, ni habla mal de
nadie. Es un excelente señor; á su oficina y no más. Da lástima
hacerle daño, y sería completo si se le volviese C la H de su
apellido; pero llámalo h.
En cuanto al de la guerra nadie sabe una palabra de él.
En mi última te pintaba en globo la confusión que en el Estamento y
fuera de él había causado la ley electoral, y te añadía:
«Yo por el pronto sólo veo clara una cosa, y es que para el 22 de
marzo se reunirán de nuevo en Madrid otras Cortes... que para
entonces es probable que empecemos á entendernos... y que
seguramente no tendremos facción, porque estarán al caer los seis
meses de la promesa, ó no tendremos ministerio, si no la cumple,
porque estará caído, etc.».
De todas esas profecías sólo en la primera acerté; porque en cuanto
á entendernos da gusto. Unos dicen que Mendizábal es el primer
hombre del mundo; otros que no es tal, sino el último; que el primero
es Istúriz y Galiano; te advierto que éste son dos: otros que ni Istúriz
ni Mendizábal: no sé qué te diga: quién asegura que esto puede
durar unos quince días, quién defiende que durará más que un
constipado mal curado: éste no ve más que el prestigio que tiene
todavía en las provincias, el cual no se destruye tan fácilmente,
sobre todo cuando no deja de tener algún fundamento; aquél no
atiende más que al descrédito en que ha caído en sus corros y
cafés, y cree que toda la nación puede juzgarle con igual talento, y
tan de cerca como él. Éstos disputan que no hay hombres aquí;
aquéllos que sí hay hombres; los de la izquierda que hay dinero; los
de la derecha que no hay un cuarto; estoy por éstos. Quién opina
que la guerra es inacabable; quién la da por acabada; añadiendo
que no falta más que tirar una línea: uno dice que el mal de España
no tiene remedio; otro que ésa es la mejor señal, que empieza la
revolución, y que en Francia sucedía lo mismo, á pesar de que todo
era diferente; varios juzgan que el rigor es de justicia, y que el árbol
de la libertad se riega con sangre: algunos creen que la humanidad
repugna tales horrores: no falta quien piensa que es guerra de
empleos, y sobra quien no piensa ni eso ni nada. Pero todos somos
liberales y vamos á una: eso sí. Por lo cual esto se acabará pronto
de un modo ó de otro: en prueba de ello te puedo decir que se
empiezan ya á acabar dos cosas: el dinero y la paciencia.
Pero son tantas las opiniones en fin y los hechos que se acumulan,
y tantas las cosas que van á suceder, sin contar las que han
sucedido desde la apertura de las Cortes, que me es indispensable
reservarlas para otras cartas: me limito en ésta á ponerme al
corriente, saliendo del atraso de noticias en que te tenía. En lo
sucesivo aprovecharé todas las ocasiones posibles de escribirte, y
al siguiente correo para Francia recibirás la inmediata, salvo
extravío, golpe de mano airada, ó caso fortuito.
Si en el ínterin, y en medio de este conflicto de opiniones
encontradas, me pides la mía, te contaré un caso que juzgo
oportuno.
Sitiaban los Franceses al mando del mariscal Moncey esa misma
Valencia, que en distintas épocas han mandado el Cid y Carratalá.
Reuniéronse en tan grave apuro el ayuntamiento y las personas
más ricas del pueblo, entre las cuales quedóse dormido de
confusión y pesadumbre un confitero, que entendía más de
ramilletes que de disturbios políticos. Iba diciendo cada uno en la
asamblea su opinión como mejor lo entendía. Llegada que le fué su
vez á nuestro hombre,—y usted, le dijo sacudiéndole del brazo el
que á su lado tenía, ¿qué piensa?—Sí, ¿cuál es su opinión de
usted?, preguntaron todos á un tiempo; á cuya pregunta contestó
despertando y todo despavorido el confitero: ¡¡¡mi opinión, sí, mi
opinión, señores, es de que Dios nos asista!!! En cuyo voto imitaba
el confitero la rara discreción del padre Froilán Díaz, confesor de
Carlos II.
Eso mismo opino yo, Andrés mío, por ahora, y mientras no vea
levantarse en masa á la nación para ahogar de una vez y para
siempre el monstruo que en el norte nos devora, en vez de
entretenerse en cuestiones secundarias y en rencillas personales,
de las cuales debiera el país hacer justicia, como del orgullo
mezquino y de la loca vanidad de sus dueños.—Tu amigo,—Fígaro.
FIN DEL TOMO SEGUNDO
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must, at
no additional cost, fee or expense to the user, provide a copy, a
means of exporting a copy, or a means of obtaining a copy upon
request, of the work in its original “Plain Vanilla ASCII” or other
form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com