使用循环查找 watir 中所有匹配的对象
Using loops to find all matching objects in watir
我正在尝试制作一个脚本,通过循环查找 table 中某个元素的所有实例。我可以识别 一个 对象,它的第一个实例:
b.table(id: "table_id").a.title
=> "foo bar"
但是当我尝试遍历 table 时,我 运行 遇到了问题:
def get_titles
titles = ""
b.table(id: "table_id").a.title.each do |title|
titles << title
end
puts titles
end
get_titles
NoMethodError: undefined method `each' for "foo bar":String
我认为我尝试遍历 table 的方式有问题。
你做错了。正确的方法是:
def get_titles
titles = ""
b.tables(id: "table_id").each do |table|
titles << table.a.title
end
puts titles
end
b.table(id: "table_id").a.title
给了你一个String
对象,你在这个字符串对象上调用了#each
。这就是错误的原因。
根据 评论,明确的方法是:
b.table(id: "table_id").links.map(&:title).join
如对其他答案的评论中所述,问题是您试图在单个 object 上使用 .each 方法,而不是某种形式的 collection.
要获得一个 collection 包含某个容器内所有标题的文件,请使用 .titles 方法
titles = b.tables(id: "table_id").titles
if you need something like a collection of all the text of the titles
b.tables(id: "table_id").titles.each do |title|
titles << title.text
end
您也可以使用贾斯汀在他对第一个答案的评论中给出的内容
我正在尝试制作一个脚本,通过循环查找 table 中某个元素的所有实例。我可以识别 一个 对象,它的第一个实例:
b.table(id: "table_id").a.title
=> "foo bar"
但是当我尝试遍历 table 时,我 运行 遇到了问题:
def get_titles
titles = ""
b.table(id: "table_id").a.title.each do |title|
titles << title
end
puts titles
end
get_titles
NoMethodError: undefined method `each' for "foo bar":String
我认为我尝试遍历 table 的方式有问题。
你做错了。正确的方法是:
def get_titles
titles = ""
b.tables(id: "table_id").each do |table|
titles << table.a.title
end
puts titles
end
b.table(id: "table_id").a.title
给了你一个String
对象,你在这个字符串对象上调用了#each
。这就是错误的原因。
根据
b.table(id: "table_id").links.map(&:title).join
如对其他答案的评论中所述,问题是您试图在单个 object 上使用 .each 方法,而不是某种形式的 collection.
要获得一个 collection 包含某个容器内所有标题的文件,请使用 .titles 方法
titles = b.tables(id: "table_id").titles
if you need something like a collection of all the text of the titles
b.tables(id: "table_id").titles.each do |title|
titles << title.text
end
您也可以使用贾斯汀在他对第一个答案的评论中给出的内容