Selenium webdriver无法点击页面外部的链接 [英] Selenium webdriver can't click on a link outside the page

查看:1040
本文介绍了Selenium webdriver无法点击页面外部的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到Selenium WebDriver的问题。我尝试点击窗口页面之外的链接(您需要向上滚动才能看到它)。我当前的代码是相当标准的:

I am having an issue with Selenium WebDriver. I try to click on a link that is outside the window page (you'd need to scroll up to see it). My current code is fairly standard:

menuItem = driver.findElement(By.id("MTP"));
menuItem.click();
// I also tried menuItem.sendKeys(Keys.RETURN);

我知道我可以向上滚动,在这种情况下可以工作。但是,如果你有一个长列表的项目,你不一定知道你有多远,你必须向下滚动。

I know I could scroll up, and it would work in this case. But in a case where you have a long list of items, you don't necessarily know how far you have to scroll down.

有任何方法可以点击不在页面可见部分的链接(但如果滚动,则会显示该链接)?

Is there any way to click on a link that is not on the visible part of the page (but that would be visible if you scroll)?

注意,我使用的是Firefox,但我打算使用IE7 / 8/9和Chrome。

As a side note, I'm using Firefox, but I am planning to use IE7/8/9 and Chrome as well.

任何帮助将非常感激。

编辑:恐怕我不能给出源代码,因为我工作的公司不允许,但我可以给我想要点击的链接的代码:

I'm afraid I can't give the source code, as the company I work for doesn't allow it, but I can give the code of the link I want to click on:

<div class="submenu">
  <div id="MTP">Link title</div>
</div>

当链接可见时,完全相同的代码工作,只有当它不是不工作。

The exact same code works when the link is visible, only when it is not does it not work.

Edit2:实际上,奇怪的是,它不会引发任何异常,只是转到下一条指令。所以基本上会发生什么:

Actually, oddly enough, it doesn't raise any exception and just goes to the next instruction. So basically, what happens is:

menuItem = driver.findElement(By.id("MTP")); // no exception
menuItem.click();  // no exception
//... some code ensuring we got to the next page: timeout reached
driver.findElement(By.id("smLH")).click(); // NoSuchElementException, as we're on the wrong page.


推荐答案

实际上可以自动滚动到element。虽然这不是一个很好的解决方案(在这种情况下(必须有一种方法,使其工作,而不滚动)我将发布它作为解决方法。我希望有人会想出更好的主意...

It is actually possible to scroll automatically to element. Although this is not a good solution in this case (there must be a way to get it working without scrolling) I will post it as a workaround. I hope someone will come up with better idea...

public void scrollAndClick(By by)
{
   WebElement element = driver.findElement(by);
   int elementPosition = element.getLocation().getY();
   String js = String.format("window.scroll(0, %s)", elementPosition);
   ((JavascriptExecutor)driver).executeScript(js);
   element.click();
}

这篇关于Selenium webdriver无法点击页面外部的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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