java moveToElement() 执行悬停操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42135675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
moveToElement() to perform a hover action
提问by Gabriel Abel
Can somebody help showing why this is not working?
有人可以帮助说明为什么这不起作用吗?
Page Object:
页面对象:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
public class NavBarPO {
WebDriver driver;
Actions action;
public NavBarPO(WebDriver driver){
this.driver = driver;
PageFactory.initElements(driver, this);
action = new Actions(driver);
}
@CacheLookup
@FindBy(how = How.CSS, using = "li.menu-item.menu-item-type-taxonomy.menu-item-object-wpsc_product_category.menu-item-has-children.has_children > a")
private WebElement product_Category;
public void hover_Product_Category(){
action.moveToElement(product_Category);
}
}
Test:
测试:
public class OpenDemos {
@BeforeTest
public void Initialize() {
System.setProperty("webdriver.chrome.driver", "C:/Users/u6028938/Documents/Selenium Java/chromedriver.exe");
System.setProperty("webdriver.gecko.driver", "C:/Users/u6028938/Documents/Selenium Java/geckodriver.exe");
}
@Test
public void SecondTest() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
NavBarPO nav = new NavBarPO(driver);
driver.get("http://www.store.demoqa.com");
Thread.sleep(3000);
nav.Hover_Product_Category();
System.out.println("Successfully Executed Test!");
Thread.sleep(10000);
driver.quit();
}
}
The nav.hover_Product_Category()simply does nothing, not even an error. When i use .click()instead of .moveToElement()the element is clicked and the dropdown that i want is displayed, so the selector is correct.
在nav.hover_Product_Category()简单地什么也不做,甚至不是一个错误。当我使用.click()而不是.moveToElement()单击元素并显示我想要的下拉列表时,选择器是正确的。
回答by Guy
You need to call perform()on Actionsclass methods
你需要调用perform()的Actions类的方法
public void hover_Product_Category(){
action.moveToElement(product_Category).perform();
}
回答by Gabriel Abel
The function moveToElementdoes not work correctly in FirefoxDriver. The solution is to change the tests to ChromeDriver. If you need to test Firefox you can replace moveToElementwith click.
该功能moveToElement在FirefoxDriver. 解决方案是将测试更改为ChromeDriver. 如果您需要测试 Firefox,您可以替换moveToElement为click.

