0

我正在使用 mechanize 并且在一个表单上遇到问题...该表单有两个同名的选择框。

如何选择第二个?

IE。NumNights 第二次出现。

我在文档中发现了这样的内容:

form.set_fields( :foo => ['bar', 1] )

但这不起作用:

form.field_with(:name => [ 'NumNights', 2 ]).options[no_days.to_i-1].select
4

2 回答 2

2

获取对表单的引用,并遍历成员。像这样的东西:

my_fields = form.fields.select {|f| f.name == "whatever"}
my_fields[1].whatever = "value"

填写完表格后,提交。我没有运行这段代码,但我认为它应该可以工作。

于 2009-09-23T12:49:46.517 回答
0

Geo 有一个不错的解决方案,但也有一些错失的机会。

如果您只找到一个元素,那么使用 Enumerable#find 而不是 Enumerable#select 然后 Array#first 可能更有效。或者,您可以在选择期间简单地进行重新分配。

如果您查看建议的方法,如果找不到具有该名称的字段,您可能会触发异常:

# Original approach
my_fields = form.fields.select {|f| f.name == "whatever"}
# Chance of exception here, calling nil#whatever=
my_fields[1].whatever = "value"

我提倡使用 Enumerable#select 并简单地在循环内完成工作,这样更安全:

my_fields = form.fields.select do |f|
  if (f.name == "whatever")
    # Will only ever trigger if an element is found,
    # also works if more than one field has same name.
    f.whatever = 'value'
  end
end

另一种方法是使用 Enumerable#find 最多返回一个元素:

# Finds only a single element
whatever_field = form.fields.find { |f| f.name == "whatever" }
whatever_field and whatever_field.whatever = 'value'

当然,您总是可以在代码中添加异常捕获,但这似乎适得其反。

于 2009-09-23T14:29:15.633 回答