如何使用PageFactory编写鼠标悬停

时间:2017-01-10 20:52:39

标签: selenium drop-down-menu mouseover pageobjects

我的代码应该点击下拉菜单中的值,我有这个代码:

WebElement element = driver.findElement(By.xpath("//a[text()='Product Category']"));
Actions action = new Actions(driver);
action.moveToElement(element).perform();
waitForElementToBeDisplayed(driver.findElement(By.xpath("//a[text()='iMacs']")), 500);
WebElement subElement = driver.findElement(By.xpath("//a[text()='iMacs']"));
action.moveToElement(subElement);
action.click();
action.perform();

我试图重写你的代码,我用PageFactory写道:

WebElement element = mouse_over_product_category;
Actions action = new Actions(driver);
action.moveToElement(element).perform();
waitForElementToBeDisplayed(driver.findElement(By.xpath("//a[text()='iMacs']")), 500);
WebElement subElement = link_iMacs;
action.moveToElement(subElement);
action.click();
action.perform();

我的错误是:

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

有人可以帮我怎么写。我是初学者。

2 个答案:

答案 0 :(得分:0)

WebElement element=driver.findElement(By.xpath("//a[text()='Product Category']"));        
String mouseOver = "var evObj = document.createEvent('MouseEvents');" +
                            "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" +
                            "arguments[0].dispatchEvent(evObj);";


   ((JavascriptExecutor)driver).executeScript(mouseOver, element);

这是使用JavaScript

答案 1 :(得分:0)

这两种方法不止这样做。

尝试使用以下方法完成您的需要:

//Conventional Way- Identifying the Select Menu Box and sending the text desired to select either by Text or Index or by value



    WebElement elDropDownItem = driver.findElement(By.xpath(""));

                if (elDropDownItem != null) {
                    Select comboBox = new Select(elDropDownItem);

//Either of these 3 should work SelectBy-- should work
                        comboBox.selectByVisibleText(MenuItemText);
                        break;
            //OR        
                        comboBox.selectByIndex(Integer
                                .parseInt(MenuItemIndex));
                        break;
            //OR        
                        comboBox.selectByValue(MenuItemValue);
                        break;
                    }

另一种方式:

//Clicking the down arrow and then clicking on the Select Item you desire
            WebElement element= driver.findElement(By.xpath("downArrow"));
            element.click();

WebElement element1= driver.findElement(By.xpath("selectMenuItem"));
            element1.click();