如何點選跨瀏覽器使用 Selenium Webdriver?
我們可以使用 Selenium Webdriver 在各個瀏覽器中點選帶有 <input type= file> 的按鈕。首先,我們需要藉助 xpath 或 css 之類的定位符來識別元素,然後應用 sendKeys() 方法,其中傳入了要上傳的檔案路徑。
讓我們看看具有檔案輸入型別的元素的 HTML 程式碼。元素在螢幕上的對應表示如下。
為了使用此元素,我們需要先與“瀏覽”按鈕進行互動,並且要上傳的檔案路徑應有效。
示例
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; public class TypeFile{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url ="https://tutorialspoint.tw/selenium/selenium_automation_practice.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify element WebElement l=driver.findElement(By.cssSelector("input[type='file']")); // file path passed with sendkeys() l.sendKeys("C:\Users\ghs6kor\Pictures\Desert.jpg"); driver.quit(); } }
輸出
廣告