我正在使用 Actions class 移动到一个元素,但我无法单击下拉列表中的元素

I am using Actions class to move to an element but I am unable to click the elements in the dropdown

public static void main() throws InterruptedException {
        Thread.sleep(5000);
        Actions a = new Actions(driver);
        WebElement as = driver.findElement(By.xpath(".//*[@id='yourAccount']"));
        a.moveToElement(as).build().perform();
        WebElement login = driver.findElement(By.xpath("//ul[@class='hFlyout guest gnf_nav_depth2_list']//li[12]//button"));
        System.out.println(login.isDisplayed());
        login.click();
        Thread.sleep(5000);
        driver.switchTo().frame(1);
        System.out.println("pass");
        driver.findElement(By.linkText("Join for free")).click();
        Thread.sleep(5000);
}

您不应使用 Thread.sleep(),因为这是一种不好的做法。请改用 WebDriverWait

从您的代码来看,您的悬停看起来是正确的,但您需要稍等片刻以确保面板打开并且 "Join for free" 按钮可见且可点击。 WebDriverWait 可以轻松解决这个问题...您只需等待按钮可点击,然后点击它即可。

driver.get("https://www.sears.com/");
Actions hover = new Actions(driver);
hover.moveToElement(driver.findElement(By.id("yourAccount"))).build().perform();
new WebDriverWait(driver, 3).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[data-action='join']"))).click();

这段代码适合我。