Selenium webdriver can't click on a link outsi

2020-01-25 07:09发布

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)?

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

Any help would be greatly appreciated.

Edit: 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.

10条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-25 08:00

This works for me (in c#)-

item = driver.findelement(by.....);
item.SendKeys(Keys.LeftControl);
item.Click();
查看更多
Luminary・发光体
3楼-- · 2020-01-25 08:02

This solution worked like a charm for me:

public void click(By by) throws Exception{
    WebElement element = driver.findElement(by);
    ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
    Thread.sleep(500);
    element.click();
}
查看更多
ゆ 、 Hurt°
4楼-- · 2020-01-25 08:04

I posted this same answer in another question so this is just a copy and paste.

I once had a combo box that wasn't in view that I needed to expand. What I did was use the Actions builder because the moveToElement() function will automatically scroll the object into view. Then it can be clicked on.

WebElement element = panel.findElement(By.className("tabComboBoxButton"));

Actions builder = new Actions(this.driver);

builder.moveToElement(element);
builder.click();
builder.build().perform();

(panel is simply a wrapped element in my POM)

查看更多
The star\"
5楼-- · 2020-01-25 08:05

Instead of move the scrollbar to the button position, which sometimes it didn't work for me, I send the enter key to the button

var element = driver.FindElement(By.Id("button"));
element.SendKeys(Keys.Enter);
查看更多
登录 后发表回答