首页 > 解决方案 > 无法使用 selenium webdriver 和 Java 单击登录按钮

问题描述

嗨,我正在尝试自动化https://www.nextgenerationautomation.com并且无法使用 Selenium 4 单击登录/注册按钮

脚步:

  1. 导航到 URL:https ://www.nextgenerationautomation.com
  2. 单击登录/注册按钮。

问题:当我使用时Thread.Sleep,代码工作正常,但是当我使用显式等待和隐式等待时,它不起作用。
我在驱动程序初始化时在我的基类中添加了隐式。

这是我尝试过的代码。

public class nextGenAutomationLoginPage extends Base {

    @FindBy(xpath = "(//button[@class='_1YW_5'])[1]")
    WebElement login;

    public nextGenAutomationLoginPage() {
        super();
        PageFactory.initElements(driver, this);
        // TODO Auto-generated constructor stub
    }

    public void clickOnLogin() throws InterruptedException {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        System.out.println(driver.getTitle());
        // Thread.sleep(2000);
        wait.until(ExpectedConditions.elementToBeClickable(login));
        //wait.until(ExpectedConditions.presenceOfNestedElementLocatedBy(login, By.xpath("//div[@class='_10b1I']") ));
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
        js.executeScript("arguments[0].scrollIntoView();", login);
        login.click();
        //driver.findElement(By.xpath("(//button[@class='_1YW_5'])[1]")).click();
        wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//div[@id='comp-kaoxkn4a1']")));
        String sign = driver.findElement(By.xpath("//div[@id='comp-kaoxkn4a1']/h1/span")).getText();
        System.out.println(sign);
    }

注意:我也尝试添加滚动以在单击之前添加一些等待。

DOM: 在此处输入图像描述 如果我在这里遗漏了什么,请告诉我。

标签: javaseleniumselenium-webdriverxpathwebdriverwait

解决方案


嗨,我明白这里发生了什么:

  1. 手动导航到 URL:https ://www.nextgenerationautomation.com (Selenium 也加载此 URL)
  2. 手动立即继续点击“登录/注册按钮”(Selenium 也可以点击,因此控制台中没有错误)
  3. 除非在此处输入图像描述(LinkedIn 以下计数小部件)出现在屏幕上,否则“登录/注册”页面不会打开
  4. 一旦在此处输入图像描述就会出现手动单击“登录/注册按钮”,现在登录页面正在打开(Selenium 可以在 Thread.Sleep 之后单击)

总结:

  1. 这是该页面上的编码缺陷。
  2. “登录/注册”不可点击,直到 在此处输入图像描述 被添加到页面上
  3. 你的硒代码非常好:)
  4. 我使用的 Xpath 是//span[text()='Log In / SignUp']

谢谢KS


推荐阅读