Search code examples
rubynokogirimechanize

Open filled-form page in ruby


I'm using mechanize to fill out a form, but I want to review it on the webpage before submission. The goal is to open a browser with the pre-filled form.

require 'mechanize'

mechanize = Mechanize.new
page = mechanize.get('https://www.linuxtoday.com/contribute.html')

form = page.form_with :name => 'upload'
form.sub_name = "mbb"
form.email = "[email protected]"
form.author_name = "Mr Potatohead"
form.title = "Mr Potatohead writes Ruby"
form.link = "https://potato.potato"
form.body = "More text"

`open #{page.uri}`

Calling out to the operating system to open the site is, of course, empty form. I don't see a page.open or similar method available. Is there a way to achieve this (using mechanize or other gems)?


Solution

  • As others have mentioned in the comments try selenium, you'll need chrome or firefox driver installed, here's example with chrome to get you started:

    require 'selenium-webdriver'
    require 'pry' # optional
    
    driver = Selenium::WebDriver.for :chrome
    
    driver.navigate.to 'https://www.linuxtoday.com/contribute.html'
    form = driver.find_element(id: 'upload')
    form.find_element(id: 'sub_name').send_keys 'mbb'
    form.find_element(id: 'email').send_keys '[email protected]'
    
    binding.pry # or sleep 60 
    driver.quit
    

    For more instructions see documentation