Selenium 中 click() 的替代方案
Selenium webdriver 中的点击方法有几种替代方案。我们可以使用 JavaScript Executor 执行点击操作。Selenium 可以使用 executeScript 方法执行 JavaScript 命令。
参数 – arguments[0].click() 和将执行点击操作的元素定位符传递给此方法。
语法
WebElement n=driver.findElement(By.linkText("Refund"));
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click();", n);示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JsClickLink{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//launch URL
driver.get("https://tutorialspoint.com/index.htm");
// identify element
WebElement m = driver.findElement(By.xpath("//a[@title='TutorialsPoint - Home']"));
// click with Javascript Executor
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click();", m);
driver.quit();
}
}如果我们想在具有提交值的 type 属性的 form 标签中单击提交按钮,可以使用 submit 方法来完成。
我们让一个按钮的 html 代码具有 form 标签中的 type=submit。

示例
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 ClsNameStrategy{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.linkedin.com/");
// identify element
WebElement l = driver.findElement(By.className("input__input"));
l.sendKeys("test@gmail.com");
WebElement x = driver.findElement(By.id("session_password"));
x.sendKeys("1258147");
WebElement m = driver.
findElement(By.cssSelector("button[type='submit']"));
//click button with type submit
m.submit();
driver.close();
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP