WebDriver 的 click() 与 JavaScript 的 click()。
我们可以使用 webdriver 的 click 和 Javascript 的 click 来点击链接。对于 Selenium webdriver 点击链接,我们可以使用链接文本和部分链接文本定位器。我们可以使用 driver.findElement(By.linkText()) 和 driver.findElement(By.partialLinkText()) 方法来点击。
html 代码中的链接包含在锚标记中。锚标记中包含的链接文本作为参数传递给 driver.findElement(By.linkText(<link text>)) 方法。锚标记中包含的部分匹配链接文本作为参数传递给 driver.findElement(By.partialLinkText(<partial link text>)) 方法。最后,要点击链接,使用 click 方法。
让我们看看具有锚标记的链接的 html 代码。

示例
代码实现。
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
public class DriverClick{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://tutorialspoint.com/about/about_careers.htm");
// identify link with link text locator
driver.findElement(By.linkText("Write for us")).click();
System.out.println("Page title after click: " + driver.getTitle());
}
}我们还可以使用 Selenium 中的 Javascript Executor 执行诸如点击链接之类的 Web 操作。我们将使用 executeScript 方法,并将 argument index.click() 和要点击的 webelement 作为参数传递给该方法。
示例
使用 Javascript executor 的代码实现。
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.By;
public class DriverClickJs{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://tutorialspoint.com/about/about_careers.htm");
// identify link
WebElement l = driver.findElement(By.linkText("Write for us"));
//click link with Javascript Executor
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click();", l);
System.out.println("Page title after click: " + driver.getTitle());
}
}输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP