如何使用watir-webdriver循环访问链接数组的href [英] How to access href of array of links in a loop using watir-webdriver

查看:104
本文介绍了如何使用watir-webdriver循环访问链接数组的href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个某些<a>元素的数组,如下所示:

I've got an array of certain <a> elements like this:

array = browser.as(:class => 'foo')

我尝试转到这样的链接:

I try to go to the links like this:

$i = 0
while $i < num do
    browser.goto array[$i].href
    .
    .
    .
    $i += 1
end

哪个适用于第一个循环,但不适用于第二个循环.为什么会这样呢?如果我愿意

Which works the for the first loop, but not for the second. Why is this happening? If I do

puts array[1].href
puts array[2].href
puts array[-1].href

之前

browser.goto array[$i].href

它显示了终端窗口中第一个循环上的所有链接.

it shows all the links on the first loop in terminal window.

推荐答案

比我更了解这一点的人需要进行验证/澄清.我的理解是,页面加载时会为元素提供引用.加载新页面时,即使每个页面上的链接看起来都一样,您也会构建所有新参考.

Someone who knows this better than I do will need to verify / clarify. My understanding is that elements are given references when the page is loaded. On loading a new page you are building all new references, even if it looks like the same link on each page.

您要存储对该元素的引用,然后要求它继续进行操作并从中拉出href属性.由于该元素仍然存在,因此它第一次起作用.新页面一旦加载,就不再存在.提取属性的请求失败.

You are storing a reference to that element and then asking it to go ahead and pull the href attribute from it. It works the first time, as the element still exists. Once the new page has loaded it no longer exists. The request to pull the attribute fails.

如果您只关心hrefs,那么可以使用一种更短,更Ruby的方法.

If all you care about are the hrefs there's a shorter, more Ruby way of doing it.

array = []

browser.as(:class => 'foo').each { |link|
  array << link.href
}

array.each { |link| 
  browser.goto link
}

通过将链接填充到数组中,我们不必担心陈旧的引用.

By cramming the links into the array we don't have to worry about stale references.

这篇关于如何使用watir-webdriver循环访问链接数组的href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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