How to get 'value' of select tag based on content of select tag, using Nokogiri

纵然是瞬间 提交于 2019-12-23 01:52:34

问题


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:


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


来源:https://stackoverflow.com/questions/2346257/how-to-get-value-of-select-tag-based-on-content-of-select-tag-using-nokogiri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!