Selenium測試直接運行在瀏覽器中,就像真正的用戶在操作一樣。支持的瀏覽器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。

Selenium簡介
Selenium是一個用于Web應用程序自動化測試工具。Selenium測試直接運行在瀏覽器中,就像真正的用戶在操作一樣。支持的瀏覽器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。
Selenium特點
- 開源、免費
- 多瀏覽器支持:FireFox、Chrome、IE、Opera、Edge;
- 多平臺支持:Linux、Windows、MAC;
- 多語言支持:Java、Python、Ruby、C#、JavaScript、C++;
- 對Web頁面有良好的支持;
- 簡單(API 簡單)、靈活(用開發語言驅動);
- 支持分布式測試用例執行。
Selenium優勢
- 自動化測試:可以編寫程序實現對系統自動化測試。
- 爬蟲:適用爬取js混淆加密的網頁。
案例演示
下載驅動包
谷歌下載地址:
???http://chromedriver.storage.googleapis.com/index.html??
說明:盡量下載與自己谷歌瀏覽器相近的版本,否則會出現不可描述的錯誤。
引入依賴
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version>
</dependency>
<!-- selenium 瀏覽器測試 不添加此依賴有可能會拋com.google.common.util.concurrent.SimpleTimeLimiter.create異常-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>RELEASE</version>
</dependency>
代碼--"HelloWorld"
private WebDriver driver;
// 瀏覽器驅動路徑
String browserDriverPath = "F:/IDEAWork/code-tools/webDriveSpider/chromedriver.exe";
public static void main(String[] args) throws Exception {
Spider app = new Spider();
app.setUp("https://news.baidu.com/");
}
public void setUp(String url) throws Exception {
// 啟動chrome瀏覽器
System.setProperty("webdriver.chrome.driver", browserDriverPath);
ChromeOptions options = new ChromeOptions();
// 無瀏覽器模式
options.addArguments("--no-sandbox");
driver = new ChromeDriver(options);
driver.manage().window().maximize();// 最大化瀏覽器
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);// 設置操作超時時長,該設置是全局性的,即所有操作都最長等待30s
driver.get(url);
}
看看這效果,簡直了!?
爬蟲方式代碼
List<WebElement> webElements = driver.findElements(By.className("a3"));
for (WebElement webElement : webElements) {
System.out.println(webElement.getText());
}
只供教學參考,切勿違規使用。結果如下:
文本框錄入內容并跳轉
WebElement webElement = driver.findElement(By.id("kw"));
webElement.sendKeys("新聞");
WebElement searchBouuton = driver.findElement(By.id("su"));
searchBouuton.click();

每天一個小知識,每天進步一點點!?