views:

333

answers:

1

How would one get the contents of the 'value' attribute of a select tag, based on content of the select tag (i.e. the text wrapped by option), using Nokogiri?

For example, given the following HTML:

<select id="options" name="options">
  <option value="1">First Option - 4</option>
  <option value="2">Second Option - 5</option>
  <option value="3">Third Option - 6</option>
</select>

I would like to be able to specify a string (e.g. 'First Option') and have the contents of the 'value' attribute returned (e.g. '1').

I have been able to achieve the inverse of this (get the content of the select tag based the 'value' attribute of the select tag), but this isn't quite what I need to do.

+1  A: 

Try this:

require 'nokogiri'
require 'open-uri'

url = "abc.html"
doc = Nokogiri::HTML(open(url))
doc.xpath('//select[@id="options"]/option[contains(., "First Option")]').each do | node|
  p node['value']
end
KandadaBoggu
Perfect - thank you!
Sai