2

I am attempting to have selenium click on links, which are within li elements. This is happening inside a while loop. The clicks are working until I reach an li which is below the level of the Firefox window. If I manually scroll down in the Firefox webdriver window before selenium attempts the click, the click will work without error.

Here is the java code I'm using for the click. Menu_item_module is an int which increases by 1 each time the loop runs to move down the list. The webelement below references the li element.

driver.findElement(By.id("digitalVellum_dijit_MenuListItem_" + menu_item_module)).click();

Here is a code snippet containing one of the li elements from the page in question.

<li id="digitalVellum_dijit_MenuListItem_11" class="dijitLayoutContainer dijitContainer menuListItem level1 item-22 closed dijitLayoutContainer-child dijitLayoutContainer-dijitLayoutContainer" data-dojo-attach-event="onclick:click" data-dojo-attach-point="containerNode" widgetid="digitalVellum_dijit_MenuListItem_11">
<a href="#" data-dojo-attach-point="_link" tabindex="0">
<span class="expander" data-dojo-attach-event="onclick:_toggleState"></span>
<span class="label">Overview</span>
<div class="clearoutfloats"> </div>
</a>
<ul id="digitalVellum_dijit_MenuList_2" class="mainMenu dijitLayoutContainer dijitContainer dijitLayoutContainer-child dijitLayoutContainer-dijitLayoutContainer" data-dojo-attach-point="containerNode" widgetid="digitalVellum_dijit_MenuList_2">
</li>

I have tried to have selenium scroll by using the following code.

JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript("window.scrollBy(0,100)", "");

This appears to have no effect. I think that may be because the scroll area is a frame, not the entire page. Regardless, I didn't think I should need to scroll at all. I thought webdriver will scroll automatically when necessary to select an element.

Any help or insight would be much appreciated.

Thanks, Steve Archibald

4

2 回答 2

3

即使元素不在视图中(隐藏),您也可以在其上执行 javascript:

JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript("arguments[0].click();", element);

element您要单击的元素在哪里。

于 2013-11-11T08:01:10.680 回答
0

我认为您需要在单击之前等待元素,尤其是在循环中进行操作时。像其他人建议的那样,也尝试最大化窗口。可能这将有助于 WebDriver 准确地找到 WebElement 的坐标,但我不是 100% 确定。但我相信你需要WebDriverWait。试试这个,

WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 300/*seconds*/);
driver.manage().window().maximize();
driver.get("http://www.bbc.com/");
for (int menu_item_module = 0; menu_item_module < 10; menu_item_module++) {
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By
                        .id("digitalVellum_dijit_MenuListItem_"
                                +menu_item_module)));
            element.click();
}
于 2013-11-09T23:43:57.323 回答