Joe
Joe

Reputation: 293

Choosing form fields by label using Mechanize?

I originally wrote 800 lines to do this, site by site. However, on talking to a couple of people, it seems like my code is way longer than it needs to be.

So, I've got an idea of what you'd do in Python, with a particular Egg, but I'm working with Ruby. So, does anyone have any idea how to enter details in a form field, based on what the label for it is, rather than the id/name? Using Mechanize.

Upvotes: 1

Views: 389

Answers (1)

pguardiario
pguardiario

Reputation: 54984

Let's say your html looks like:

<label>Foo</label>
<input name="foo_field">

You can get the name of the input following a specific label:

name = page.at('label[text()="Foo"] ~ *[name]')[:name]
#=> "foo_field"

and use that to set the form value

form[name] = 'bar'

Upvotes: 2

Related Questions