100% found this document useful (2 votes)
34 views

Get Getting Started with PhantomJS Beltran Aries free all chapters

Beltran

Uploaded by

elyonkalkacs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
34 views

Get Getting Started with PhantomJS Beltran Aries free all chapters

Beltran

Uploaded by

elyonkalkacs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Getting Started with PhantomJS Beltran Aries

https://textbookfull.com/product/getting-started-with-
phantomjs-beltran-aries/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Getting Started with Kubernetes 2nd Edition Baier

https://textbookfull.com/product/getting-started-with-kubernetes-2nd-
edition-baier/

textboxfull.com

Make Getting Started with Processing py Allison Parrish

https://textbookfull.com/product/make-getting-started-with-processing-
py-allison-parrish/

textboxfull.com

Getting Started with Gulp - Second Edition Travis Maynard

https://textbookfull.com/product/getting-started-with-gulp-second-
edition-travis-maynard/

textboxfull.com

Getting Started with EEG Neurofeedback John N. Demos

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

Getting Started with Microsoft System Center Operations


Manager Kevin Greene

https://textbookfull.com/product/getting-started-with-microsoft-
system-center-operations-manager-kevin-greene/

textboxfull.com

Getting Started with Advanced C# 1st Edition Vaskaran


Sarcar [Sarcar

https://textbookfull.com/product/getting-started-with-advanced-c-1st-
edition-vaskaran-sarcar-sarcar/

textboxfull.com

Getting Started with Natural Language Processing MEAP V06


Ekaterina Kochmar

https://textbookfull.com/product/getting-started-with-natural-
language-processing-meap-v06-ekaterina-kochmar/

textboxfull.com

Programming With STM32: Getting Started With the Nucleo


Board and C/C++ Donald Norris

https://textbookfull.com/product/programming-with-stm32-getting-
started-with-the-nucleo-board-and-c-c-donald-norris/

textboxfull.com
Getting Started with
PhantomJS

Harness the strength and capabilities of PhantomJS to


interact with the web and perform website testing with a
headless browser based on WebKit

Aries Beltran

BIRMINGHAM - MUMBAI
Getting Started with PhantomJS

Copyright © 2013 Packt Publishing

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.

First published: November 2013

Production Reference: 1191113

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78216-422-7

www.packtpub.com

Cover Image by Abhishek Pandey ([email protected])


Credits

Author Project Coordinator


Aries Beltran Joel Goveya

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

Aries Beltran is a software developer located in Manila, Philippines. He works as


an architect and R&D developer for financial businesses using web and enterprise
technologies. He is currently developing new tools to provide real-time insights. He
is interested in playing around with cutting-edge HTML5 development and mobile
visualization. When he isn't coding, he likes to take photos of his daughter, Tara,
who is his favorite model.

I would like to thank my family, Cecille and Tara, for inspiring


me always and giving me courage to aim higher. I would also
like to thank Phil Sales for helping me in every aspect of this book.
Lastly, I would like to thank all of the people that I work with at
Packt Publishing, who are very supportive and understanding.
About the Reviewers

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).

He is also a member of the Python Software Foundation and a former member


of the Association for Computing Machinery and the GNOME Foundation.

I would like to thank my wife, Anne and my daughter, Margaux.


www.PacktPub.com

Support files, eBooks, discount offers and more


You might want to visit www.PacktPub.com for support files and downloads related
to your book.

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

Free Access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib
today and view nine entirely free books. Simply use your login credentials for immediate access.
Table of Contents
Preface 1
Chapter 1: Getting Started 7
Downloading PhantomJS 7
Building PhantomJS from source 8
Working with PhantomJS 9
PhantomJS JavaScript API 13
The Module API 14
The WebPage API 14
The System API 14
The FileSystem API 14
The WebServer API 15
The phantom object 15
The command-line arguments 15
The script argument 16
The debug option 16
The cookie-file option 16
Writing PhantomJS scripts 16
Summary 17
Chapter 2: Manipulating Page Content 19
Opening a web page 19
Playing with DOM elements 22
Selecting elements 22
Simulating mouse clicks 30
PhantomJS event triggering 30
DOM event triggering 33
Working with form fields 34
Summary 39
Table of Contents

Chapter 3: Handling Events and Callbacks 41


Listening to page events 41
Page load events 41
When a resource is requested 43
Receiving a page resource 45
Two stages of the resource received event 48
Knowing when the URL changes 51
Capturing alert messages 52
Answering prompt messages 53
Responding to confirm pop ups - OK or Cancel 53
Performing user events 54
Keyboard events 54
Mouse events 57
Summary 58
Chapter 4: Capturing Errors 59
Handling PhantomJS errors 59
Capturing page script errors 62
Anticipating the page loading error 64
Exiting with error codes 66
Summary 66
Chapter 5: Grabbing Pages 67
Undocumented supported image format 70
Screenshot dimensions 71
Saving web pages as PDFs 73
Summary 74
Chapter 6: Accessing Location-based Services 75
Checking a location based on IP address 75
Getting driving directions 77
Looking up for pizza delivery establishments 80
Summary 82
Chapter 7: Working with Files 83
PhantomJS FileSystem API 83
Reading files 84
Checking for file existence 84
Opening the file 85
Closing the opened files 87
Writing files 87
Character encoding 88
Summary 88

[ 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.

What this book covers


Chapter 1, Getting Started, starts by introducing what PhantomJS is, how to get and
install it, and then goes directly into creating your very first script.

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 6, Accessing Location-based Services, focuses on using existing web-based


and location-based services. Using PhantomJS as our headless browser, we will
be capturing location data and creating examples that are useful.

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 8, Cookies, discusses how cookies are supported by PhantomJS. We will


learn to create cookies and interact with the pages that need them.

Chapter 9, External JavaScript, addresses the subject of working with external


JavaScripts and shows how we can create PhantomJS modules that can be
re-used in every script.

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.

What you need for this book


You will need a Windows, Mac OS, or a Linux-based environment where you can
develop and work with the examples given in this book. You will definitely need
PhantomJS binaries, which will be discussed in Chapter 1, Getting Started, where we
will learn how to get and install them.

Who this book is for


This book is intended for those who are interested in developing cool scripts and
having fun at the same time, using JavaScript and PhantomJS. If you are a complete
novice in JavaScript, this is not the book for you. You should also have working
knowledge of HTML and CSS, but you don't need to be an advanced user.

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."

A block of code is set as follows:


var system = require('system');
var url = system.args[1];

var page = require('webpage').create();


page.onLoadStarted = function () {
console.log('Page Loading Started');
};

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)

Any command-line input or output is written as follows:


$ ./phantomjs pageload3.js http://www.google.com
Loading takes 6.751 seconds.
0.255 seconds : http://www.google.com/
0.379 seconds : http://www.google.com.ph/
0.213 seconds : http://ssl.gstatic.com/gb/images/b_8d5afc09.png
0.676 seconds : http://www.google.com.ph/images/srpr/logo1w.png
0.561 seconds : http://www.google.com.ph/images/srpr/nav_logo80.png
6.135 seconds : http://www.google.com.ph/xjs/_/js/hp/sb_he,pcc/rt=j/ver=_
aDh7zAWqI8.en_US./d=1/sv=1/rs=AItRSTOgg467Qcx4GftzMMz3ZDPd84lcog

[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."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

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.

To send us general feedback, simply send an e-mail to [email protected],


and mention the book title via the subject of your message.

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.

Downloading the example code


You can download the example code files for all Packt books you have purchased
from your account at http://www.packtpub.com. If you purchased this book
elsewhere, you can visit http://www.packtpub.com/support and register to
have the files e-mailed directly to you.

[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.

Please contact us at [email protected] with a link to the suspected


pirated material.

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

Download your binaries based on your preference of operating system. After


downloading, extract the binaries to any folder you desire. That's it! Your
PhantomJS binary is ready to be used.

Add PhantomJS to PATH


Add the /bin folder of PhantomJS into your $PATH OS to make it
easier when calling PhantomJS main binary. This allows us to call
the binary anywhere without specifying the full path.

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.

Quick PhantomJS install on Mac OS X


As an alternative to downloading the precompiled binary, we can
install PhantomJS using brew:
brew update && brew install phantomjs
For more information about brew, visit http://brew.sh/.

Building PhantomJS from source


You may also want to build your own binaries by compiling PhantomJS from source.
Sources are hosted in the Github server at https://github.com/ariya/phantomjs.

Before you start downloading sources, you will need these tools installed on
your workspace:

OS Required development tools


Windows Visual Studio 2010 or 2008
(Express edition)
git
Mac OS X Xcode
git

[8]
Chapter 1

OS Required development tools


Ubuntu/ gcc
RHEL/ gcc-c++
CentOS
Linux make
git
openssl-devel
freetype-devel
fontconfig-devel

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.

Working with PhantomJS


Now, let's see how PhantomJS's magic works. It is a command-line-based
application, so we need to execute it in an OS terminal or console. The PhantomJS
package contains a series of files and comes with one main executable file, which is
named phantomjs.

Open your terminal and then navigate to your PhantomJS bin folder. In the prompt,
execute phantomjs without any arguments.

PhantomJS Windows build


In Windows build, PhantomJS executable can be found in the
root folder with the filename phantomjs.exe.

[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

"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X)


AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.7.0
Safari/534.34",
"webSecurityEnabled": true
},
"args": []
}
phantomjs>

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.

If we trap the error code in a shell script, it will look as follows:


#!/bin/bash
bin/phantomjs
OUT=$?
if [ $OUT -eq 0 ];then
echo "Done."
else
echo "Ooops! Failed.!"
fi

[ 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.!
$

Use the interactive mode to experiment with the PhantomJS API.

Before we begin creating PhantomJS scripts, we first need to make a quick


roundup of the PhantomJS JavaScript API.

Downloading the example code


You can download the example code files for all Packt books you have
purchased from your account at http://www.packtpub.com. If you
purchased this book elsewhere, you can visit http://www.packtpub.
com/support and register to have the files e-mailed directly to you.

PhantomJS JavaScript API


PhantomJS runs JavaScript and comes with a JavaScript API to make your life easy.
It extends the standard JavaScript API and adds richer layers of capabilities, such as
allowing us access to the underlying file system, ease of access and manipulation of
DOM objects, system and environment variable gathering. It even gives us the ability
to inject custom scripts into the web page.

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

The Module API


While writing custom objects and API sets, you may want to create custom modules
that will make your life easier. You can do that in PhantomJS using the Module
API. It allows you to create your own modules and import it anywhere in your
implementation. The built-in modules are webpage, system, fs (File System),
and webserver.

The WebPage API


PhantomJS is a headless browser. Accessing and manipulating web documents are
its core functionalities, and that's what the WebPage API is used for. The WebPage
API allows us to access, control, and manipulate web documents. It provides a rich
interface to easily reference and extract page details including document content. It
enables capturing of events, such as page loading, when an error occurs within the
page, or when navigating to another page is requested, and so on. It is also capable of
capturing pages and saving them as images. And more importantly, it allows you to
manipulate documents on the fly and traverse DOM as you do with any web page.
This is enormously valuable for writing automated user interface tests—for example,
you can force click events or post forms, and capture the results—as well as standard
web scraping of public URLs.

The System API


The System module provides system-level functionalities ranging from OS
information, environment variables, command-line arguments, and process-related
properties. The System module is very useful as you engage more in developing
applications with PhantomJS.

The FileSystem API


Accessing files, writing to text files, or just reading a custom configuration file—these
are tasks that can be done with PhantomJS. FileSystem provides a standard API to
perform file I/O. You can read, write, and delete files; you can even list folder files.

FileSystem has 31 functions to manage and manipulate files within PhantomJS. We


have been using this set extensively, and it helps solve several problems without fail.
Writing JSON data to a file is very basic, but you will find it much easier using the
FileSystem API.

[ 14 ]
Chapter 1

The WebServer API


Perhaps you have a grand idea, but it requires you to process a web request and
execute a PhantomJS script on it. PhantomJS can do that; you can embed your
own web server implementation using the WebServer API within your PhantomJS
application. This feature is marked as experimental, but it does work, and with
roughly five lines of code you can have your own web server running.

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


The phantom object is your reference to PhantomJS within your scripts that allows
you to access certain properties and provides functionality that affects the entire
script (such as quitting the application as previously mentioned.) The phantom object
can be directly referenced anywhere in the script and does not need to be explicitly
imported. You may also access it as a child of the global window object.

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.

The command-line arguments


There are a few command-line arguments that we need to understand before
plunging into writing PhantomJS scripts. The syntax of the PhantomJS argument is:
phantomjs [switches] [options] [script] [argument [argument [...]]]

All of the arguments are optional. Using the command without arguments will bring
up the interactive mode.

[ 15 ]
Getting Started

The script argument


The script argument is the name of a script file. It can be a relative or an absolute
path and must follow the path convention of the host system OS.
phantomjs /scripts/chapter1.js

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.

The debug option


The debug option enables the printing of additional warnings and the debug
messages. This is very useful when debugging your script. It accepts either
yes or no as the value of the option, and no is the default value.

phantomjs --debug=yes /scripts/chapter1.js

The cookie-file option


If you are working on pages that require persistent cookies, you need to enable this
option. This option will accept a file path where cookies will be saved and read.
phantomjs --cookie-file=/scripts/cookies.txt /scripts/chapter1.js

Writing PhantomJS scripts


We know how to write JavaScript, and now we know that there are several
PhantomJS JavaScript APIs and objects. We also have learned the basics of the
PhantomJS command-line arguments. We are now ready to create our own scripts.

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

PARIS.—ÉDOUARD BLOT, IMPRIMEUR, RUE BLEUE, 7


*** END OF THE PROJECT GUTENBERG EBOOK OBRAS
COMPLETAS DE FÍGARO, TOMO 2 ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright
in these works, so the Foundation (and you!) can copy and
distribute it in the United States without permission and without
paying copyright royalties. Special rules, set forth in the General
Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree to
abide by all the terms of this agreement, you must cease using
and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project
Gutenberg™ works in compliance with the terms of this
agreement for keeping the Project Gutenberg™ name
associated with the work. You can easily comply with the terms
of this agreement by keeping this work in the same format with
its attached full Project Gutenberg™ License when you share it
without charge with others.

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. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it
away or re-use it under the terms of the Project Gutenberg
License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country where
you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of the
copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute
this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

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.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• 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 provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt that
s/he does not agree to the terms of the full Project Gutenberg™
License. You must require such a user to return or destroy all
copies of the works possessed in a physical medium and
discontinue all use of and all access to other copies of Project
Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite
these efforts, Project Gutenberg™ electronic works, and the
medium on which they may be stored, may contain “Defects,”
such as, but not limited to, incomplete, inaccurate or corrupt
data, transcription errors, a copyright or other intellectual
property infringement, a defective or damaged disk or other
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like