gpt4 book ai didi

ruby - 显式等待 Selenium Webdriver

转载 作者:数据小太阳 更新时间:2023-10-29 07:31:45 26 4
gpt4 key购买 nike

研究试图理解显式等待的方法。

    require 'rubygems'
require 'selenium-webdriver'
require 'cucumber'

$driver = Selenium::WebDriver.for :firefox
$driver.manage.timeouts.implicit_wait = 3

Then /^do search$/ do
driver = $driver
one_way = driver.find_element(:id, "search.ar.type.code.oneWay").click
sleep 5
from = driver.find_element :xpath => "//div[@class = 'origin column1']//input[@type = 'text']"
from.click

所以在 one_way 单选按钮被点击并且输入表单改变后,所以我把 sleep 5 给它一个时间元素出现,否则会出现错误“element not可见的 ...”。所以我认为现在是了解显式等待的好时机,因为我需要等到元素出现。

    wait = Selenium::WebDriver::Wait.new(:timeout => 40)
wait.until {from = driver.find_element(:xpath, "//div[@class = 'origin column1']//input[@type = 'text']")
from.click
}

但是出现错误“Selenium::WebDriver::Error::ElementNotVisibleError:元素当前不可见,因此可能无法与之交互”。为什么此代码不等到元素出现并单击它?

最佳答案

问题是该元素还不在 DOM 中,因此您需要在其中放置一个时间延迟。

也就是说,API doco for ruby说你应该这样做

require 'rubygems' # not required for ruby 1.9 or if you installed without gem
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :firefox
driver.get "http://somedomain/url_that_delays_loading"

wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds
begin
element = wait.until { driver.find_element(:id => "some-dynamic-element") }
ensure
driver.quit
end

请注意,您随后可以 .click() 的元素是从 wait.until 方法分配的,而不是代码中的 find_element() 方法。

然而,任意延迟并不总是有效,如果站点繁忙,则延迟可能不够长。更好的选择是等待元素变得可点击或可见。

Java API 有 ExpectedConditions convenience methods cn 可以这样使用...

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
element.click();

不幸的是,我认为 Ruby 还没有这个。您可能需要编写自己的 ExpectedCondition 类或包。

我不是 Ruby 开发人员,但这里有一个 Java 函数的想法,可用于实现您的 ExpectedCondition

public WebElement findElementInTime(WebDriver driver, By by, int timeoutInSeconds)
{
log.debug("==================+>>>>>> looking for element for "+ timeoutInSeconds + " seconds");
WebElement ret = null;

for (int second = 0; second < timeoutInSeconds; second++) {
try { if (isElementPresent(driver,by)) {
log.debug("found element :-)");
ret = driver.findElement(by);
break;
}} catch (Exception e) {

log.debug("oops... sleeping 1 sec wait for button");
}
log.debug("sleeping 1 sec wait for button");
}
return ret;
}

关于ruby - 显式等待 Selenium Webdriver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34889248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com