之前在使用JAVA做爬蟲的時候,有遇到一個問題,是有些網站,必須要瀏覽器運行,然后JS執行.內容才能顯示出來.遇到這種站,代碼直接趴了,內容抓取不到.網上找了一下發現有一個叫selenium的,可以模擬瀏覽器行為,做自動化測試.感覺這個應該挺好玩的.難得有時間.玩了一把.確實不錯
官方網站: http://www.seleniumhq.org/
官方代碼倉庫: https://github.com/SeleniumHQ/selenium
我的項目使用的依賴管理工具是maven,下面給出Selenium的maven地址
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.4.0</version>
</dependency>
<!-- 大家平時找jar包可以在這個網站:https://mvnrepository.com/ 去查詢,非常好用 -->
然后寫一個入門測試的程序
package org.linuxsogood.reference.chp1.selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
/**
* Created by honway on 2017/6/14 10:44.
*
*/
public class Demo1 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\opt\driver\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://192.168.0.227:7700/");
WebElement username = driver.findElement(By.xpath("//*[@id="loginForm"]/div/div[2]/input"));
username.sendKeys("123456");
WebElement passwd = driver.findElement(By.xpath("//*[@id="loginForm"]/div/div[3]/input"));
passwd.sendKeys("123456");
driver.findElement(By.xpath("//*[@id="loginForm"]/div/div[5]/button")).submit();
driver.findElement(By.xpath("//*[@id="menu_li"]/li[2]/a")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//*[@id="menu_li"]/li[2]/ul/li[9]")).click();
}
}
由于selenium的運行是基于瀏覽器的,所以這里要下載一個webdriver,把下載下來的webDriver放到一個目錄里面,然后使用System工具類設置一下系統變量,指向這個webDriver
對于每一種瀏覽器,都會有一個webDriver, 其實這個webDriver是一個瀏覽器的驅動.用它來控制我們本地安裝的對應的瀏覽器.我例子當中使用的是chrome的驅動器.
請注意:這里只需要設置驅動器對應的環境變量,不是你的chrome瀏覽器程序的exe文件所在的位置.是你下載的驅動器程序的位置.
附上官方的驅動器下載地址 http://chromedriver.storage.googleapis.com/index.html
程序中有一個線程暫停了2秒的代碼,是因為點擊菜單,它有一個動畫效果,如果不暫時一會兒再點擊,會選擇不到元素,從而拋出異常.