Java之selenium實現模擬谷歌瀏覽器操作
阿新 • • 發佈:2021-09-17
僅此記錄下使用過程,入門水平。
環境準備
基本依賴
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我始終記住:青春是美麗的東西,而且對我來說,它永遠是鼓舞的源泉。——(現代)巴金