如何使用 Selenium WebDriver 單擊谷歌搜尋?
我們可以用 Selenium webdriver 點選谷歌搜尋。首先,我們需要使用任意一個定位器,如 id、類、名稱、xpath 或 css 來識別搜尋編輯框。
接下來,我們將使用 sendKeys() 方法輸入一些文字。接下來,我們必須使用任意一個定位器,如 id、類、名稱、xpath 或 css 來識別搜尋按鈕,最後應用 click() 方法或直接應用 submit() 方法。我們將等待在滿足 presenceOfElementLocated 預期條件的情況下出現搜尋結果。
我們需要 import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait 來納入期望條件和 WebDriverWait** 類。此概念源自同步中的顯式等待條件。
讓我們嘗試實現以下場景。
示例
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.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; public class SearchAction{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.google.com/"); // identify element WebElement p=driver.findElement(By.name("q")); //enter text with sendKeys() then apply submit() p.sendKeys("Selenium Java"); // Explicit wait condition for search results WebDriverWait w = new WebDriverWait(driver, 5); w.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//ul"))); p.submit(); driver.close(); } }
輸出
廣告