使用Nokogiri,如何根据选择标签的内容获取选择标签的“价值” [英] How to get 'value' of select tag based on content of select tag, using Nokogiri

查看:113
本文介绍了使用Nokogiri,如何根据选择标签的内容获取选择标签的“价值”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Nokogiri,将如何获取select标签的value属性的内容(基于选项包装的文本)?

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?

例如,给定以下HTML:

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>

我希望能够指定一个字符串(例如First Option),并具有内容返回的'value'属性(例如'1')。

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.

推荐答案

尝试这样: / p>

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

这篇关于使用Nokogiri,如何根据选择标签的内容获取选择标签的“价值”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆