SlideShare a Scribd company logo
The Agent                                                        Accessing page elements                                                      Forms
                                                              # The current page                                                    # Submitting a form without a button:
 require 'rubygems'                                                                                                                 form.submit
                                                              agent.page
 require 'mechanize'
                                                              # The HTML page content                                               # Submitting a form with the default button
 agent = WWW::Mechanize.new                                   page.body                                                             form.click_button()

 # disable keep_alive, when running into                      # forms, links, frames                                                # Submitting a form with a specific button
 # problems with session timeouts or getting an               page.forms, page.links, frames                                        form.click_button(form.button_with(:name => 'OK')
 # EOFError
                                                              # Selecting by criteria follows the pattern:                          # Form elements
 agent.keep_alive = false                                                                                                           form.fields, form.buttons, form.file_uploads, form.radio_buttons,
                                                              # page.element(s)_with(:criteria => value)
                                                              # The plural form (.elements) returns an                              form.checkboxes
 # Setting user agent:                                        # array, the singular form (.element) the
 agent.user_agent = 'Friendly Mechanize Script"               # first matching element or nil. Criteria                             # Form elements can be selected just like page elements
                                                              # is an attribute symbol and value may be                             # form.element(s)_with(:criteria => value)
 # Using one of the predefined user agents:                   # a string or a regular expression. If no                             # e.g.:
 # 'Mechanize', 'Mac Mozilla', 'Linux Mozilla'.               # criteria attributr is given, :name will                             form.field_with(:name => 'password')
                                                              # be used. e.g.:                                                      form.field_with('password')
 # 'Windows IE 6', 'iPhone', 'Linux Konqueror',
                                                              page.form_with(:name => 'formName')                                   form.checkboxes(:value => /view_.*/)
 # 'Windows IE 7', 'Mac FireFox', 'Mac Safari',
                                                              page.form_with('formName')
 # 'Windows Mozilla'                                                                                                                # Field values can also be selected directly by their name
                                                              page.links_with(:text => /[0-9]*/
 agent.user_agent_alias = 'Mac Safari'                                                                                              form.password = 'secret'

 # To verify server certificates:                                                                                                   # Setting field values
 # (A collection of certificates is available                                                                                       # field       : .value = 'something'
 # here: http://curl.haxx.se/ca/ )                                                                                                  # checkbox    : .(un)check / .checked = true|false
                                                                                                                                    # radio_button: .(un)check / .checked = true|false
 agent.ca_file = 'cacert.pem'
                                                                                                                                    # file_upload : .file_name = '/tmp/upload.dat'


                                                                            Ruby / Mechanize
                                                                                                                                    # e.g.:
 # Don't follow HTTP redirects                                                                                                      form.field_with('foo').value = 'something'
 agent.redirect_ok = false                                                                                                          form.checkbox_with(:value => 'blue').uncheck
                                                                                        http://mechanize.rubyforge.org/mechanize/   form.radio_buttons[3].check
 # Follow refresh in meta tags
 agent.follow_meta_refresh = true                                                               Nokogiri                            # Select lists / drop down fields:
                                                                                                                                    form.field_with('color').option[2].select
                                                                                                   http://nokogiri.org/             form.field_with('color').options.find{|o| o.value == 'red'}.select
 # Enable logging
                                                                                                                                    form.field_with('color').select_none
 require 'logger'                                                                                                                   form.field_with('color').select_all
 agent.log = Logger.new('mechanize.log')


                                                                                                                                                    Parsing the page content
                                                                                                                                    # Selecting elements from the documents DOM
                                                                                     Hello Mechanize!                               nodes = agent.page.search('expression')
                                                                                                                                    nodes = agent.page / 'expression'
                                                             require 'rubygems'
                                                             require 'mechanize'
           Navigation/History                                                                                                       # Selecting the first matching element or nil
                                                             agent = WWW::Mechanize.new                                             node = agent.page.at('expression')
# load a page                                                agent.get('http://rubyforge.org/')
agent.get('http://the.internet.net')                                                                                                # 'expression' might be an XPath or CSS selector
                                                             agent.page.forms.first.words = 'mechanize'                             nodes = agent.page.search('//h2/a[@class="title"]')
# Go back to the last page:                                  agent.page.forms.first.click_button                                    nodes = agent.page.search('.h2 a.title')
agent.back
                                                             agent.page.link_with(:text => /WWW::Mechanize/).click
                                                             agent.page.link_with(:text => 'Files').click
                                                                                                                                    # navigating the document tree:
# Follow a link by its text
agent.link_with(:text => 'click me').click                                                                                          node.parent
                                                             links = agent.page / 'strong/a'                                        node.children
# Backup history, execute block and                          version = links.find do |link|
# restore history                                              link['href'] =~ /shownotes.*release_id/                              # node content and attributes
agent.transact do                                            end.text                                                               node.text
  ...                                                                                                                               node.inner_html
end                                                          puts "Hello Mechanize #{version}!"
                                                                                                                                    node.attributes['width']

                                                                                                                                    # found nodes, can be searched the same way
                                                                                                                                    rows = agent.page / 'table/tr'
Version 2010-01-30                           Creative Commons License                                                               value = rows[0].at('td[@class="value"]').text
(c) 2010 Tobias Grimm                        http://creativecommons.org/licenses/by/3.0

More Related Content

PDF
HTML::FormFu talk for Sydney PM
Dean Hamstead
 
KEY
Getting started with Rails (2), Season 2
RORLAB
 
PDF
Fb request form guide
tamirc
 
PDF
Working With The Symfony Admin Generator
John Cleveley
 
PDF
Curso Symfony - Clase 4
Javier Eguiluz
 
PPTX
Html5
Akash Tripathi
 
PDF
Fórum de Software Livre do Serpro RJ 2009
Fabio Akita
 
HTML::FormFu talk for Sydney PM
Dean Hamstead
 
Getting started with Rails (2), Season 2
RORLAB
 
Fb request form guide
tamirc
 
Working With The Symfony Admin Generator
John Cleveley
 
Curso Symfony - Clase 4
Javier Eguiluz
 
Fórum de Software Livre do Serpro RJ 2009
Fabio Akita
 

What's hot (20)

PDF
Rails <form> Chronicle
Kyosuke MOROHASHI
 
PDF
Curso Symfony - Clase 2
Javier Eguiluz
 
PDF
Drupal8 simplepage v2
Samuel Solís Fuentes
 
PPTX
Routing in Drupal 8
kgoel1
 
PPTX
Routing in Drupal 8
kgoel1
 
PDF
Rails MVC by Sergiy Koshovyi
Pivorak MeetUp
 
PDF
Everything you always wanted to know about forms* *but were afraid to ask
Andrea Giuliano
 
PDF
Taming forms with React
GreeceJS
 
PDF
Django Templates
Willy Liu
 
PDF
Django Bogotá. CBV
ctrl-alt-delete
 
PPTX
Service approach for development REST API in Symfony2
Sumy PHP User Grpoup
 
PDF
Ajax nested form and ajax upload in rails
Tse-Ching Ho
 
PDF
Leveraging Symfony2 Forms
Bernhard Schussek
 
PDF
Send, pass, get variables with php, form, html & java script code
Noushadur Shoukhin
 
PDF
Ch9 .Best Practices for Class-Based Views
Willy Liu
 
DOC
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
Atlassian
 
PDF
Template rendering in rails
Hung Wu Lo
 
PPTX
Building Potent WordPress Websites
Kyle Cearley
 
KEY
Building Web Service Clients with ActiveModel
pauldix
 
PPTX
Service approach for development Rest API in Symfony2
Sumy PHP User Grpoup
 
Rails <form> Chronicle
Kyosuke MOROHASHI
 
Curso Symfony - Clase 2
Javier Eguiluz
 
Drupal8 simplepage v2
Samuel Solís Fuentes
 
Routing in Drupal 8
kgoel1
 
Routing in Drupal 8
kgoel1
 
Rails MVC by Sergiy Koshovyi
Pivorak MeetUp
 
Everything you always wanted to know about forms* *but were afraid to ask
Andrea Giuliano
 
Taming forms with React
GreeceJS
 
Django Templates
Willy Liu
 
Django Bogotá. CBV
ctrl-alt-delete
 
Service approach for development REST API in Symfony2
Sumy PHP User Grpoup
 
Ajax nested form and ajax upload in rails
Tse-Ching Ho
 
Leveraging Symfony2 Forms
Bernhard Schussek
 
Send, pass, get variables with php, form, html & java script code
Noushadur Shoukhin
 
Ch9 .Best Practices for Class-Based Views
Willy Liu
 
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
Atlassian
 
Template rendering in rails
Hung Wu Lo
 
Building Potent WordPress Websites
Kyle Cearley
 
Building Web Service Clients with ActiveModel
pauldix
 
Service approach for development Rest API in Symfony2
Sumy PHP User Grpoup
 
Ad

Viewers also liked (9)

DOCX
Khóa học đánh dj chuyên nghiệp
Góc chia sẻ
 
PDF
Curso tablet e lousa
Naiara Batista
 
DOC
Vinay Sharma Resume
VINAY KUMAR SHARMA
 
DOCX
Official Resume
Erin McCarty
 
PDF
Ravindra_Resume
ravindra jamuar
 
PDF
Diet clinic noida health care
pkdietclinic
 
DOCX
Entrenamiento del dia jueves 21 06-2012
Diego Rojas
 
PDF
saabab_cbrne_transportpackaging_2015_web
Peter Richards
 
DOCX
Mulut
fitriyutari
 
Khóa học đánh dj chuyên nghiệp
Góc chia sẻ
 
Curso tablet e lousa
Naiara Batista
 
Vinay Sharma Resume
VINAY KUMAR SHARMA
 
Official Resume
Erin McCarty
 
Ravindra_Resume
ravindra jamuar
 
Diet clinic noida health care
pkdietclinic
 
Entrenamiento del dia jueves 21 06-2012
Diego Rojas
 
saabab_cbrne_transportpackaging_2015_web
Peter Richards
 
Ad

Similar to SAVIA (20)

PDF
Functional testing with capybara
koffeinfrei
 
PDF
Capybara
Flavian Missi
 
PDF
Advanced RESTful Rails
Viget Labs
 
PDF
Advanced RESTful Rails
Ben Scofield
 
PDF
JavaServer Faces 2.0 - JavaOne India 2011
Arun Gupta
 
PDF
Ember.js for Big Profit
CodeCore
 
PDF
The Rails Way
Michał Orman
 
PPTX
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface
 
PDF
Cmsc 100 (web forms)
MaeEstherMaguadMaralit
 
PPTX
From Ruby to Node.js
jubilem
 
ODP
Iktomi lightning talk
Harut Dagesian
 
PDF
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Arun Gupta
 
PPT
68837.ppt
BruceLee275640
 
DOCX
Tony Vitabile .Net Portfolio
vitabile
 
PDF
R Tanenbaum .Net Portfolio
Robert Tanenbaum
 
PDF
Web I - 04 - Forms
Randy Connolly
 
PPTX
Sencha Touch - Introduction
ABC-GROEP.BE
 
PDF
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
PPTX
Devise and Rails
William Leeper
 
DOCX
Rhino Mocks
Anand Kumar Rajana
 
Functional testing with capybara
koffeinfrei
 
Capybara
Flavian Missi
 
Advanced RESTful Rails
Viget Labs
 
Advanced RESTful Rails
Ben Scofield
 
JavaServer Faces 2.0 - JavaOne India 2011
Arun Gupta
 
Ember.js for Big Profit
CodeCore
 
The Rails Way
Michał Orman
 
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface
 
Cmsc 100 (web forms)
MaeEstherMaguadMaralit
 
From Ruby to Node.js
jubilem
 
Iktomi lightning talk
Harut Dagesian
 
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Arun Gupta
 
68837.ppt
BruceLee275640
 
Tony Vitabile .Net Portfolio
vitabile
 
R Tanenbaum .Net Portfolio
Robert Tanenbaum
 
Web I - 04 - Forms
Randy Connolly
 
Sencha Touch - Introduction
ABC-GROEP.BE
 
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
Devise and Rails
William Leeper
 
Rhino Mocks
Anand Kumar Rajana
 

Recently uploaded (20)

PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
Doc9.....................................
SofiaCollazos
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 

SAVIA

  • 1. The Agent Accessing page elements Forms # The current page # Submitting a form without a button: require 'rubygems' form.submit agent.page require 'mechanize' # The HTML page content # Submitting a form with the default button agent = WWW::Mechanize.new page.body form.click_button() # disable keep_alive, when running into # forms, links, frames # Submitting a form with a specific button # problems with session timeouts or getting an page.forms, page.links, frames form.click_button(form.button_with(:name => 'OK') # EOFError # Selecting by criteria follows the pattern: # Form elements agent.keep_alive = false form.fields, form.buttons, form.file_uploads, form.radio_buttons, # page.element(s)_with(:criteria => value) # The plural form (.elements) returns an form.checkboxes # Setting user agent: # array, the singular form (.element) the agent.user_agent = 'Friendly Mechanize Script" # first matching element or nil. Criteria # Form elements can be selected just like page elements # is an attribute symbol and value may be # form.element(s)_with(:criteria => value) # Using one of the predefined user agents: # a string or a regular expression. If no # e.g.: # 'Mechanize', 'Mac Mozilla', 'Linux Mozilla'. # criteria attributr is given, :name will form.field_with(:name => 'password') # be used. e.g.: form.field_with('password') # 'Windows IE 6', 'iPhone', 'Linux Konqueror', page.form_with(:name => 'formName') form.checkboxes(:value => /view_.*/) # 'Windows IE 7', 'Mac FireFox', 'Mac Safari', page.form_with('formName') # 'Windows Mozilla' # Field values can also be selected directly by their name page.links_with(:text => /[0-9]*/ agent.user_agent_alias = 'Mac Safari' form.password = 'secret' # To verify server certificates: # Setting field values # (A collection of certificates is available # field : .value = 'something' # here: http://curl.haxx.se/ca/ ) # checkbox : .(un)check / .checked = true|false # radio_button: .(un)check / .checked = true|false agent.ca_file = 'cacert.pem' # file_upload : .file_name = '/tmp/upload.dat' Ruby / Mechanize # e.g.: # Don't follow HTTP redirects form.field_with('foo').value = 'something' agent.redirect_ok = false form.checkbox_with(:value => 'blue').uncheck http://mechanize.rubyforge.org/mechanize/ form.radio_buttons[3].check # Follow refresh in meta tags agent.follow_meta_refresh = true Nokogiri # Select lists / drop down fields: form.field_with('color').option[2].select http://nokogiri.org/ form.field_with('color').options.find{|o| o.value == 'red'}.select # Enable logging form.field_with('color').select_none require 'logger' form.field_with('color').select_all agent.log = Logger.new('mechanize.log') Parsing the page content # Selecting elements from the documents DOM Hello Mechanize! nodes = agent.page.search('expression') nodes = agent.page / 'expression' require 'rubygems' require 'mechanize' Navigation/History # Selecting the first matching element or nil agent = WWW::Mechanize.new node = agent.page.at('expression') # load a page agent.get('http://rubyforge.org/') agent.get('http://the.internet.net') # 'expression' might be an XPath or CSS selector agent.page.forms.first.words = 'mechanize' nodes = agent.page.search('//h2/a[@class="title"]') # Go back to the last page: agent.page.forms.first.click_button nodes = agent.page.search('.h2 a.title') agent.back agent.page.link_with(:text => /WWW::Mechanize/).click agent.page.link_with(:text => 'Files').click # navigating the document tree: # Follow a link by its text agent.link_with(:text => 'click me').click node.parent links = agent.page / 'strong/a' node.children # Backup history, execute block and version = links.find do |link| # restore history link['href'] =~ /shownotes.*release_id/ # node content and attributes agent.transact do end.text node.text ... node.inner_html end puts "Hello Mechanize #{version}!" node.attributes['width'] # found nodes, can be searched the same way rows = agent.page / 'table/tr' Version 2010-01-30 Creative Commons License value = rows[0].at('td[@class="value"]').text (c) 2010 Tobias Grimm http://creativecommons.org/licenses/by/3.0