今日份的學習,利用chromedriver的無頭特性直接訪問百度首頁
運行環境:
- windows7
- chrome 76.0.3809.100
- chromedriver 72.0.3626.69
- eclipse
步驟:
1、創建maven項目,過程略
2、pom.xml中添加依賴(目前(算不上功能的)功能這一個就夠了)
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.1</version>
<scope>compile</scope>
</dependency>
3、主函數中,創建chrome實例並訪問"http://www.baidu.com"
public static void chromeDemo1(){
WebDriver driver = null;
String url = "http://www.baidu.com"; //注意要是完整的url,有http://xxx,不然會報錯
driver = Chromedriver.getChromeDriver(); //創建chrome實例
driver.get(url); //訪問url
System.out.println(driver.getTitle()); //輸出訪問成功的url的頁面title
}
4、創建chrome實例
public class Chromedriver {
static String driverPath = "D:\\ny_software_install\\chromedriver.exe";
public static WebDriver getChromeDriver(){
System.setProperty("webdriver.chrome.driver",driverPath); //chromedriver所在路徑
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless"); //設置無頭,谷歌瀏覽器就不會蹦出來影響你了
options.addArguments("--disable-gpu");
options.addArguments("--user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36");
WebDriver driver = new ChromeDriver(options);
return driver;
}
}
注意事項:
- 下載匹配谷歌瀏覽器的chromedriver(千萬不要單純地依賴網上說的對應關係,經過我血與淚的經歷來說,不可靠,我之前下76.0.xx.xx版本的chromedriver,每次創建實例都彈出了兩個窗口(沒有設置無頭時),一個空白data;窗口,一個就是我訪問的網站,當我設置了無頭後,還是會彈出一個空白窗口)
- 訪問網站記得寫上"http/https"啥的