如何在 Selenium 中使用 Java 点击注册按钮?我可以打开页面,但无法点击。

seleniumautomation testingtesting tools

我们可以使用 Selenium 中的 Java 点击"注册"按钮。首先,我们需要借助定位器(例如 ID、类名、名称、链接文本、Xpath、CSS 或部分链接文本)来识别"注册"按钮。识别后,我们需要借助 click 方法点击"注册"按钮。

语法

WebElement m=driver. findElement(By.id("loc-txt"));
m.click();

示例

Code Implementation with click

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class SignIn{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://www.linkedin.com/");
      // 使用类名识别元素,然后使用 click 方法
      WebElement m=driver.
      findElement(By.className("sign-in-form__submit-button"));
      m.click();
      driver.close();
   }
}

此外,我们可以在 sendKeys 方法的帮助下单击"注册"按钮,并将 Keys.ENTER 作为参数传递给该方法。

语法

WebElement m=driver. findElement(By.id("loc-txt"));
m.sendKeys(Keys.ENTER);

示例

Code Implementation with sendKeys

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
public class SignInSendKeys{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://www.linkedin.com/");
      // 通过类名识别元素,然后使用 sendKeys 方法
      WebElement m=driver.
      findElement(By.className("sign-in-form__submit-button"));
      m.sendKeys(Keys.ENTER);
      driver.close();
   }
}

相关文章