How to get 'value' of select tag based on content of select tag, using Nokogiri
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">S开发者_高级运维econd 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.
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
精彩评论