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.tw/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(); } }
廣告