1、安裝docker
? ? ? ? 省略
2、拉取鏡像
docker pull selenium/standalone-chrome-debug
3、運行容器
docker run -d -p 4444:4444 -p 5900:5900 -v C:\Users\Public\VNC_Donwnloads:/home/seluser/Downloads --memory=6g --name selenium_chrome selenium/standalone-chrome-debug
其中 4444 是連接端口,5900是 vnc遠程連接接口,內存限制6g 建議設置成2g(博主主機內存大),
C:\Users\Public\VNC_Donwnloads:/home/seluser/Downloads 其中C:\Users\Public\VNC_Donwnloads 是下載主機目錄,因為博主docker在wsl內。
/home/seluser/Downloads 是容器內chrome 下載文件的地址(固定的,不用去改動)
4、連接容器桌面
連接vnc可以查看到容器內桌面,方便開發調試
下載vnc遠程連接工具 推薦下載:RealVNC? - Remote access software for desktop and mobile | RealVNC
輸入? ip:端口? 和密碼, 密碼 默認為secret
成功進入 fluxbox桌面
可以看到已經安裝好了chrome
5、編寫測試代碼?
博主使用java進行編寫?測試代碼,當然使用其他語言也是類似的
maven
<dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>4.17.0</version></dependency>
示例:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;import java.net.MalformedURLException;
import java.net.URL;public class Main {public static void main(String[] args) {WebDriver driver=null;try {// 遠程Selenium 服務器地址URL seleniumHub=new URL("http://localhost:4444/wd/hub");// 創建optionsChromeOptions options=new ChromeOptions();// 創建遠程WebDriverdriver= new RemoteWebDriver(seleniumHub,options);// 跳轉百度界面driver.get("https://www.baidu.com");// 獲取頁面htmlString html = driver.getPageSource();System.out.println(html);// 5秒后結束程序Thread.sleep(5000);}catch (Exception e){e.printStackTrace();}finally {if(driver!=null){// 關閉窗口driver.close();// 關閉程序driver.quit();}}}
}
效果:
覺得對你有幫助歡迎? ?點贊? 收藏。?