WWW::M...::Shell(3pm)
π WWW::M...::Shell(3pm) π
okay so you found the WWW::M...::Shell(3pm) page, User Contributed Perl Documentation and all π
bestie you're in the right place, sit down, this one's a banger.
β¨ NAME β¨
WWW::Mechanize::Shell β an interactive shell for WWW::Mechanize. periodt. π
π SYNOPSIS π
Straight from the command line, like:
perl -MWWW::Mechanize::Shell -eshell
or alternatively as a custom shell program via:
#!/usr/bin/perl -w
use strict;
use WWW::Mechanize::Shell;
my $shell = WWW::Mechanize::Shell->new("shell");
if (@ARGV) {
$shell->source_file( @ARGV );
} else {
$shell->cmdloop;
};
that's it. that's the entry point. iconic. β¨
π DESCRIPTION π
This module implements a www-like shell on top of WWW::Mechanize, and β the way that it also can spit out crude Perl code that recreates the whole recorded session?? obsessed. π€―
Its main use is as an interactive starting point for automating a session through WWW::Mechanize. Like, you click around in the shell, and then you get code. main character energy fr fr. π
cookie tea β β the cookie support is there, but no cookies are read from your existing browser sessions. none. zero. if you want to implement reading/writing your current browser's cookies, go see HTTP::Cookies. iykyk. πͺ
π« "WWW::Mechanize::Shell->new %ARGS" π«
This is the constructor for a new shell instance. Some of the options can be passed to the constructor as parameters. π«Ά
By default, a file .mechanizerc (respectively mechanizerc under Windows) in the user's home directory is executed before the interactive shell loop is entered. Use it to set some defaults, bestie. If you want a different filename for the rcfile, pass the rcfile parameter to the constructor:
rcfile => '.myapprc',
π§Έ agent
my $shell = WWW::Mechanize::Shell->new(
agent => WWW::Mechanize::Chrome->new(),
);
Pass in a premade custom user agent. This object must be compatible to WWW::Mechanize. Use this feature from the command line as:
perl -Ilib -MWWW::Mechanize::Chrome \
-MWWW::Mechanize::Shell \
-e"shell(agent => WWW::Mechanize::Chrome->new())"
no cap, that's the whole vibe. β¨
π "$shell->release_agent" π
Since the shell stores a reference back to itself inside the WWW::Mechanize instance, you gotta break this circular reference or it's giving clingy π. This method does this. that's it. that's the job. π«‘
π "$shell->source_file FILENAME" π
The source_file method executes the lines of FILENAME as if they were typed in. like autopilot but make it β¨manualβ¨.
$shell->source_file( $filename );
π¨ "$shell->display_user_warning" π¨
All user warnings are routed through this routine, so they can be rerouted / disabled easily. yes bestie, you have full control over the yelling. π£οΈ
π "$shell->print_paged LIST" π
Prints the text in LIST using $ENV{PAGER}. If $ENV{PAGER} is empty, prints directly to STDOUT. Most of this routine comes from the perldoc utility. respect the ancestors π«Ά
π¦ "$shell->link_text LINK" π¦
Returns a meaningful text from a WWW::Mechanize::Link object. This is (in order of precedence):
$link->text
$link->name
$link->url
first one that hits, wins. slay. π
π°οΈ "$shell->history" π°οΈ
Returns the (relevant) shell history β that is, all commands that were not solely for the information of the user. The lines are returned as a list.
print join "\n", $shell->history;
πΎ "$shell->script" πΎ
Returns the shell history as a Perl program. The lines are returned as a list. The lines do not have a one-by-one correspondence to the lines in the history. (yeah, it remixes. it's a glow-up not a copy-paste π )
print join "\n", $shell->script;
π‘ "$shell->status" π‘
status is called for status updates. little check-in moment, we love a check-in. π«Ά
π¨οΈ "$shell->display FILENAME LINES" π¨οΈ
display is called to output listings, currently from the history and script commands. If the second parameter is defined, it is the name of the file to be written, otherwise the lines are displayed to the user. πΈ
tl;dr β give it a filename, it writes a file; don't, and it just shows you the goods. π
okay hold up, we're not even done yet bestie β
π COMMANDS π
okay bestie, so the shell itself implements a whole bunch of commands. let me walk you through every single one, no skips, no skimming, we're going the full distance π«Ά
exit
Leaves the shell. that's it. bye bye π main character exit.
restart
Restart the shell.
this is mostly useful when you are modifying the shell itself. β οΈ heads up though: it doesn't work if you use the shell in oneliner mode with -e.
get
Download a specific URL.
this is used as the entry point in all sessions. like, every session starts here fr.
Syntax:
get URL
save
Download a link into a file.
if more than one link matches the RE, all matching links are saved. the filename is taken from the last part of the URL. alternatively, the number of a link may also be given. π
Syntax:
save RE
content
Display the content for the current page.
Syntax: content [FILENAME]
if the FILENAME argument is provided, save the content to the file.
a trailing "\n" is added to the end of the content when using the shell, so this might not be ideally suited to save binary files without manual editing of the produced script. π consider yourself warned bestie.
title
Display the current page title as found in the <TITLE> tag. cute little title grab, obsessed.
headers
Prints all <H1> through <H5> strings found in the content, indented accordingly. With an argument, prints only those levels; e.g., headers 145 prints H1,H4,H5 strings only. β¨
ua
Get/set the current user agent
Syntax:
# fake Internet Explorer
ua "Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)"
# fake QuickTime v5
ua "QuickTime (qtver=5.0.2;os=Windows NT 5.0Service Pack 2)"
# fake Mozilla/Gecko based
ua "Mozilla/5.001 (windows; U; NT4.0; en-us) Gecko/25250101"
# set empty user agent :
ua ""
the catfishing era, we love to see it π
links
Display all links on a page
the links numbers displayed can used by open to directly select a link to follow. (yes, the original says "can used", we keep it exactly like that, no edits, periodt β)
images
Display images on a page πΌοΈ
parse
Dump the output of HTML::TokeParser of the current content
forms
Display all forms on the current page.
form
Select the form named NAME
if NAME matches /^\d+$/, it is assumed to be the (1-based) index of the form to select. π¨ there is no way of selecting a numerically named form by its name.
dump
Dump the values of the current form
value
Set a form value
Syntax:
value NAME [VALUE]
tick
Set checkbox marks β
Syntax:
tick NAME VALUE(s)
if no value is given, all boxes are checked.
untick
Remove checkbox marks
Syntax:
untick NAME VALUE(s)
if no value is given, all marks are removed.
submit
submits the form without clicking on any button. stealth mode fr.
click
Clicks on the button named NAME.
no regular expression expansion is done on NAME. just so you know π
Syntax:
click NAME
if you have a button that has no name (displayed as NONAME), use
click ""
to click on it.
open
<open> accepts one argument, which can be a regular expression or the number of a link on the page, starting at zero. these numbers are displayed by the links function. it goes directly to the page if a number is used or if the RE has one match. otherwise, a list of links matching the regular expression is displayed.
the regular expression should start and end with /.
Syntax:
open [ RE | # ]
back
Go back one page in the browser page history. βͺ
reload
Repeat the last request, thus reloading the current page.
note that also POST requests are blindly repeated, as this command is mostly intended to be used when testing server side code. π careful bestie, that POST is going out again whether you like it or not.
browse
Open the web browser with the current page
Displays the current page in the browser.
set
Set a shell option
Syntax:
set OPTION [value]
the command lists all valid options. here is a short overview over the different options available πΈ:
autosync - automatically synchronize the browser window
autorestart - restart the shell when any required module changes
This does not work with C<-e> oneliners.
watchfiles - watch all required modules for changes
cookiefile - the file where to store all cookies
dumprequests - dump all requests to STDOUT
dumpresponses - dump the headers of the responses to STDOUT
verbose - print commands to STDERR as they are run,
when sourcing from a file
history
Display your current session history as the relevant commands.
Syntax:
history [FILENAME]
commands that have no influence on the browser state are not added to the history. if a parameter is given to the history command, the history is saved to that file instead of displayed onscreen.
script
Display your current session history as a Perl script using WWW::Mechanize. β¨ iconic behaviour honestly.
Syntax:
script [FILENAME]
if a parameter is given to the script command, the script is saved to that file instead of displayed on the console.
this command was formerly known as history.
comment
Adds a comment to the script and the history. the comment is prepended with a \n to increase readability.
fillout
Fill out the current form
interactively asks the values hat have no preset value via the autofill command. (yes, "hat", we keep the typo, no cap π)
auth
Set basic authentication credentials.
Syntax:
auth user password
if you know the authority and the realm in advance, you can presupply the credentials, for example at the start of the script π:
>auth corion secret
>get http://www.example.com
Retrieving http://www.example.com(200)
http://www.example.com>
table
Display a table described by the columns COLUMNS.
Syntax:
table COLUMNS
Example:
table Product Price Description
if there is a table on the current page that has in its first row the three columns Product, Price and Description (not necessarily in that order), the script will display these columns of the whole table.
the HTML::TableExtract module is needed for this feature. π
tables
Display a list of tables.
Syntax:
tables
this command will display the top row for every table on the current page. this is convenient if you want to find out what the exact spellings for each column are.
the command does not always work nice, for example if a site uses tables for layout, it will be harder to guess what tables are irrelevant and what tables are relevant. lowkey chaotic, we accept it π
HTML::TableExtract is needed for this feature.
cookies
Set the cookie file name πͺ
Syntax:
cookies FILENAME
autofill
Define an automatic value
sets a form value to be filled automatically. the NAME parameter is the WWW::Mechanize::FormFiller::Value subclass you want to use. for session fields, Keep is a good candidate, for interactive stuff, Ask is a value implemented by the shell.
a field name starting and ending with a slash (/) is taken to be a regular expression and will be applied to all fields with their name matching the expression. a field with a matching name still takes precedence over the regular expression.
Syntax:
autofill NAME [PARAMETERS]
Examples:
autofill login Fixed corion
autofill password Ask
autofill selection Random red green orange
autofill session Keep
autofill "/date$/" Random::Date string "%m/%d/%Y"
eval
Evaluate Perl code and print the result
Syntax:
eval CODE
for the generated scripts, anything matching the regular expression /\$self->agent\b/ is automatically replaced by $agent in your eval code, to do the Right Thing. β¨
Examples:
# Say hello
eval "Hello World"
# And take a look at the current content type
eval $self->agent->ct
source
Execute a batch of commands from a file
Syntax:
source FILENAME
versions
Print the version numbers of important modules
Syntax:
versions
timeout
Set new timeout value for the agent. effects all subsequent requests. VALUE is in seconds. β±οΈ (yes, "effects", we keep it exactly as written, no fixing bestie)
Syntax:
timeout VALUE
ct
prints the content type of the most current response.
Syntax:
ct
referrer
set the value of the Referer: header
Syntax:
referer URL
referrer URL
referer
Alias for referrer π―
response
display the last server response
"$shell->munge_code( CODE )"
Munges a coderef to become code fit for output independent of WWW::Mechanize::Shell.
"shell"
this subroutine is exported by default as a convenience method so that the following oneliner invocation works π:
perl -MWWW::Mechanize::Shell -eshell
you can pass constructor arguments to this routine as well. any scripts given in @ARGV will be run. if @ARGV is empty, an interactive loop will be started.
π SAMPLE SESSIONS π
Entering values
# Search for a term on Google
get http://www.google.com
value q "Corions Homepage"
click btnG
script
# (yes, this is a bad example of automating, as Google
# already has a Perl API. But other sites don't)
Retrieving a table
get http://www.perlmonks.org
open "/Saints in/"
table User Experience Level
script
# now you have a program that gives you a csv file of
# that table.
Uploading a file
get http://aliens:xxxxx/
value f path/to/file
click "upload"
Batch download
# download prerelease versions of my modules
get http://www.corion.net/perl-dev
save /.tar.gz$/
π¦ REGULAR EXPRESSION SYNTAX π¦
some commands take regular expressions as parameters. a regular expression must be a single parameter matching ^/.*/([isxm]+)?$, so you have to use quotes around it if the expression contains spaces:
/link_foo/ # will match as (?-xims:link_foo)
"/link foo/" # will match as (?-xims:link foo)
slashes do not need to be escaped, as the shell knows that a RE starts and ends with a slash:
/link/foo/ # will match as (?-xims:link/foo)
"/link/ /foo/" # will match as (?-xims:link/\s/foo)
the /i modifier works as expected. if you desire more power over the regular expressions, consider dropping to Perl or recommend me a good parser module for regular expressions. π
π DISPLAYING HTML π
WWW::Mechanize::Shell now uses the module HTML::Display to display the HTML of the current page in your browser. have a look at the documentation of HTML::Display how to make it use your browser of choice in the case it does not already guess it correctly. πΈ
β¨ FILLING FORMS VIA CUSTOM CODE β¨
Okay bestie, so you wanna stay all cozy inside the shell π but you also wanna fill out forms with your own custom Perl code? Say less, here's the recipe π
Code you pass to the eval command gets evaluated in the WWW::Mechanize::Shell namespace. Which means you can inject new subroutines right there, and the Callback class of WWW::Mechanize::FormFiller will pick them up like πβ¨
# Fill in the "date" field with the current date/time as string
eval sub &::custom_today { scalar localtime };
autofill date Callback WWW::Mechanize::Shell::custom_today
fillout
And this method can also pull data from shell scripts, which is lowkey iconic:
# Fill in the "date" field with the current date/time as string
# works only if there is a program "date"
eval sub &::custom_today { chomp `date` };
autofill date Callback WWW::Mechanize::Shell::custom_today
fillout
β οΈ Heads up bestie: the namespace is different between the shell and the generated script. So always fully qualify your subroutine names, either in your own namespace or in the main namespace. No half-measures, fr fr.
π GENERATED SCRIPTS π
The script command outputs a skeleton script that reproduces your actions from the current session. It pulls in WWW::Mechanize::FormFiller, which is possibly not needed π. You should add some error and connection checking afterwards β your future self will thank you, no cap.
π§© ADDING FIELDS TO HTML π§©
So if you're automating a JavaScript dependent site, you're gonna run into JavaScript like this:
<script>
document.write( "<input type=submit name=submit>" );
</script>
HTML::Form will not know about this, and it will not have provided a submit button for you (understandably so, honestly π«Ά). But if you wanna create such a submit button from inside your automation script, use this code:
$agent->current_form->push_input( submit => { name => "submit", value =>"submit" } );
This also works for other dynamically generated input fields, slay β¨
And to fake an input field from inside a shell session, use the eval command:
eval $self->agent->current_form->push_input(submit=>{name=>"submit",value=>"submit"});
And yes π the generated script should do the Right Thing for this eval as well.
π LOCAL FILES π
Wanna use the shell on a local file without setting up an http server to serve it? Mood. Just use the file: URI scheme to load it into the browser:
get file:local.html
forms
π PROXY SUPPORT π
Currently, the proxy support is realized via a call to the env_proxy method of the WWW::Mechanize object, which loads the proxies from the environment. There is no provision made to prevent using proxies (yet) π. The generated scripts also load their proxies from the environment.
π ONLINE HELP π
The online help feature is currently a bit broken in Term::Shell, but a fix is in the works π οΈ. Until then, you can re-enable the dynamic online help by patching Term::Shell:
Remove the three lines
my $smry = exists $o->{handlers}{$h}{smry}
? $o->summary($h)
: "undocumented";
in sub run_help and replace them by
my $smry = $o->summary($h);
The shell works without this patch and the online help is still available through perldoc WWW::Mechanize::Shell π
π BUGS π
Bug reports are very welcome β please use the RT interface at <https://rt.cpan.org/NoAuth/Bugs.html?Dist=WWW-Mechanize-Shell> or send a descriptive mail to bug-WWW-Mechanize-Shell@rt.cpan.org. Please try to include as much (relevant) information as possible β a test script that replicates the undesired behaviour is welcome every time! π«Ά
- The two parameter version of the
authcommand guesses the realm from the last received response. Currently a RE is used to extract the realm, but this fails with some servers resp. in some cases. Use the four parameter version ofauth, or if not possible, code the extraction in Perl, either in the final script or throughevalcommands. - The shell currently detects when you want to follow a JavaScript link and tells you that this is not supported. It would be nicer if there was some callback mechanism to (automatically?) extract URLs from JavaScript-infected links.
π TODO π
- Add XPath expressions (by moving
WWW::Mechanizefrom HTML::Parser to XML::XMLlib or maybe easier, by tacking Class::XPath onto an HTML tree) - Add
headas a command ? - Optionally silence the HTML::Parser / HTML::Forms warnings about invalid HTML.
π¦ EXPORT π¦
The routine shell is exported into the importing namespace. This is mainly for convenience so you can use the following commandline invocation of the shell like with CPAN:
perl -MWWW::Mechanize::Shell -e"shell"
π REPOSITORY π
The public repository of this module is <https://github.com/Corion/WWW-Mechanize-Shell>.
π« SUPPORT π«
The public support forum of this module is <http://perlmonks.org/>.
Β©οΈ COPYRIGHT AND LICENSE Β©οΈ
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Copyright (C) 2002-2023 Max Maischein
π AUTHOR π
Max Maischein, <corion@cpan.org>
Please contact me if you find bugs or otherwise improve the module. More tests are also very welcome !
π SEE ALSO π
WWW::Mechanize, WWW::Mechanize::FormFiller, WWW::Mechanize::Firefox
And that's a wrap bestie ππ this page ships as part of perl v5.36.0, dated 2023-08-21 β go forth and automate, you absolute icon β¨π
π¦ where this page comes from
- debian trixie: libwww-mechanize-shell-perl 0.62-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libwww-mechanize-shell-perl 0.62-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libwww-mechanize-shell-perl 0.62-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libwww-mechanize-shell-perl 0.62-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms