僅此記錄下使用過程,入門水平。
環境准備
基本依賴
1.去google下載對應瀏覽器版本和系統的驅動(其它瀏覽器同理去對應的下載即可)
2.maven項目依賴包
seleniumhq是基本API,如果沒導入guava 可能會報錯
<!-- seleniumhq --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.141.59</version> </dependency> <!--https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>27.1-jre</version> </dependency>
簡單示例
import cn.hutool.core.util.ObjectUtil; import util.FileHelper; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.springframework.core.io.ClassPathResource; import java.util.List; public class SeleniumTest { private static WebDriver.Navigation navigation; public static void main(String[] args) throws InterruptedException { //登陸測試模板 test1(); //test5(); } /** * 模擬輸入並點擊登陸的測試模板 */ public static void test1() throws InterruptedException { //首先要注冊系統屬性,如果是firefox瀏覽器,需要設置webdriver.gecko.driver(注意不是webdriver.firefox.driver) //再指定驅動放置的路徑。 System.setProperty("webdriver.chrome.driver","/xxx/driver/chromedriver"); //加一些設置 ChromeOptions options = new ChromeOptions(); //谷歌的一個限制 要關閉掉 options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"}); //控制不彈出瀏覽器 options.setHeadless(false); //創建WebDriver對象 WebDriver driver = new ChromeDriver(options); //輸入指定的url地址 //driver.get("http://www.baidu.com/"); //控制瀏覽器窗口 //driver.manage().window(). //獲取一個導航窗口 navigation = driver.navigate(); //加載到指定url navigation.to("http://www.baidu.com"); //或者 //driver.get("http://www.baidu.com"); //id選擇器獲取指定元素,清空;需要看頁面的自定義的id元素 //driver.findElement(By.id("user_name")).clear(); //模擬填用戶名 driver.findElement(By.id("user_name")).sendKeys("user"); //id選擇器獲取指定元素,清空 //driver.findElement(By.id("password")).clear(); //模擬填密碼 driver.findElement(By.id("password")).sendKeys("pass"); //模擬點擊登錄按鈕 driver.findElement(By.id("btn_login")).click(); Thread.sleep(2000); WebElement page_container = driver.findElement(By.id("app_page_container")); //以此判斷是否登錄成功 if (ObjectUtil.isNotNull(page_container)) { navigation.to("http://xxx"); System.out.println("success"); } //測試完成關閉瀏覽器 //driver.close(); } public static void test5(){ System.setProperty("webdriver.chrome.driver","path"); //創建WebDriver對象 WebDriver driver = new ChromeDriver(); //輸入指定的url地址 // driver.get("http://www.baidu.com/"); //獲取一個導航窗口 navigation = driver.navigate(); //指定登陸頁面 String path = "http://xx"; //加載到指定url navigation.to(path); try { /** * 下面通過元素選擇器對獲取到的頁面進行圖片url抽取,通過url下載。 */ List<WebElement> elements = driver.findElements(By.xpath("//div[@class='image-holder']/img")); for (WebElement element : elements) { String src = element.getAttribute("src"); //DownLoadPicture.download(src); } driver.close(); } catch (Exception e) { e.printStackTrace(); } }
驅動訪問問題
本地測試驗證基本沒什么問題,但是docker打包發到服務器上后,無法運行。
一開始想的是不是jar包的資源沒訪問到
@Test public void tesPath () { String path1 = this.getClass().getResource("/driver/chromedriver").getPath(); String path3 = service.class.getResource("/driver/chromedriver").getPath(); String path2 = new ClassPathResource("driver/chromedriver").getPath(); String path4 = this.getClass().getClassLoader().getResource("driver/chromedriver").getPath(); String path5 = service.class.getClassLoader().getResource("driver/chromedriver").getPath(); String path6 = getResourceFileByPath("/driver/chromedriver").getPath(); String path7 = getResourceFileByPath("/driver/chromedriver").getAbsolutePath(); String path8 = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath(); System.out.println(path1); System.out.println(path3); System.out.println(path2); System.out.println(path4); System.out.println(path5); System.out.println(path6); System.out.println(path7); } } //根據jar來拿文件路徑,因為jar后不存在文件的自己的路徑了 public static File getResourceFileByPath(String path) { File file = null; final String resource = path; URL res = FileHelper.class.getResource(resource); if (res.getProtocol().equals("jar")) { try { InputStream input = FileHelper.class.getResourceAsStream(resource); file = File.createTempFile("tempfile", ""); OutputStream out = new FileOutputStream(file); int read; byte[] bytes = new byte[1024]; while ((read = input.read(bytes)) != -1) { out.write(bytes, 0, read); } out.close(); file.deleteOnExit(); } catch (IOException ex) { ex.printStackTrace(); } } else { //this will probably work in your IDE, but not from a JAR file = new File(res.getFile()); } if (file != null && !file.exists()) { throw new RuntimeException("Error: File " + file + " not found!"); } return file; }
具體參照這里
各種嘗試拿文件方法,才想起來driver是個可執行文件...
拓展環境-手動
容器鏡像是ubuntu系統,大概分為兩個步驟,第一下載谷歌瀏覽器,第二下載谷歌瀏覽器驅動
下載谷歌瀏覽器
如果沒下載瀏覽器會報錯,按報錯信息來貌似沒什么有效提示,查了才知道是缺少這個的原因
unknown error: cannot find Chrome binary
基本步驟:
#拿到密鑰 wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - #更換sourceList sudo sh -c 'echo "deb https://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' #更新apt sudo apt-get update #安裝 sudo apt-get install google-chrome-stable
當然如果有被牆的話,可能要配下hosts或者更新系統基礎鏡像版本了。
下載谷歌瀏覽器驅動
得放到/usr/bin下
#示例 可查看http://chromedriver.storage.googleapis.com/index.html wget --no-verbose -O /tmp/chromedriver_linux64.zip http://chromedriver.storage.googleapis.com/index.html?path=70.0.3538.16/chromedriver_linux64.zip
拓展環境-自動
通過dockerfile實現配置接口,其實和手動添加類似。
RUN apt-get update && \ apt-get install -y gnupg wget curl unzip --no-install-recommends && \ wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \ echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list && \ apt-get update -y && \ apt-get install -y google-chrome-stable && \ CHROMEVER=$(google-chrome --product-version | grep -o "[^\.]*\.[^\.]*\.[^\.]*") && \ DRIVERVER=$(curl -s "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_$CHROMEVER") && \ wget -q --continue -P /chromedriver "http://chromedriver.storage.googleapis.com/$DRIVERVER/chromedriver_linux64.zip" && \ unzip /chromedriver/chromedriver* -d /chromedriver
遇到的問題
首次調用可以會碰到如下這個問題
Chrome報錯: error while loading shared libraries: libnss3.so libXss.so.1 libasound.so.
需安裝依賴,如果安裝不了出現依賴404NOT FOUND,需要更新系統源文件source.List
apt install libnss3-dev apt-get install libxss1 apt-get install libasound2
其次是路徑問題,沒訪問到或者文件不對等
Driver info: The driver is not executable