1 package code; 2 3 import org.openqa.selenium.By; 4 import org.openqa.selenium.WebDriver; 5 import org.openqa.selenium.WebElement; 6 import org.openqa.selenium.htmlunit.HtmlUnitDriver; 7 8 9 public class UnitDriver { 10 11 public static void main(String[] args) { 12 13 //實例化虛擬瀏覽器對象 14 WebDriver driver = new HtmlUnitDriver(); 15 //打開百度首頁 16 String url = "http://www.baidu.com"; 17 driver.get(url); 18 //定位搜索框元素 19 WebElement ele = driver.findElement(By.id("kw")); 20 //輸入需查詢內容 21 ele.sendKeys("Cheese"); 22 ele.submit(); 23 24 //獲取頁面標題 25 System.out.println("Page title is :" + driver.getTitle()); 26 //獲取頁面url 27 System.out.println("Page url is :" + driver.getCurrentUrl()); 28 //關閉driver 29 driver.close(); 30 } 31 32 }
爬蟲類場景可以采用這種方式