使用Selenium+POI實現Excel自動化批量查單詞

寫在最前

相信你們都對爬蟲很是熟悉,通常來講,利用HttpClient發送請求並獲取響應以得到想要提取的數據應該是最經常使用的方法。最近工做中頻繁使用了Selenium,在本文中,咱們將使用Selenium和POI(讀寫Excel)來完成一個入門級的自動化程序,源碼地址見附錄。java

步驟一覽

  1. 使用Maven建立工程,引入Selenium和POI依賴
  2. 下載ChromeDriver並配置環境變量
  3. 編寫Selenium查詞腳本
  4. 讀寫Excel並保存
  5. 編寫main方法,運行程序

如今開始

  1. 使用Maven建立工程,引入Selenium和POI依賴git

    1.1 下載Maven,配置環境變量web

    Windows和Mac將Maven目錄地址寫入path便可,具體步驟可百度,Google,十分常見。chrome

    1.2 在IDEA中配置Mavenapache

    IDEA自帶Maven可能版本非最新,建議自行引入本地最新版本。bash

    1.3 建立工程框架

    建立工程時只要使用最基礎的模板,也就是直接點擊next。 ide

    1.4 在mvnrepository.com搜索Selenium,POI和POI-ooxml依賴,將其引入pom.xml,並在右下角點擊import change,最終pom.xml加入內容以下:spa

    <dependencies>
         <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
         <dependency>
             <groupId>org.seleniumhq.selenium</groupId>
             <artifactId>selenium-java</artifactId>
             <version>3.14.0</version>
         </dependency>
         <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
         <dependency>
             <groupId>org.apache.poi</groupId>
             <artifactId>poi</artifactId>
             <version>4.0.0</version>
         </dependency>
         <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
         <dependency>
             <groupId>org.apache.poi</groupId>
             <artifactId>poi-ooxml</artifactId>
             <version>4.0.0</version>
         </dependency>
     </dependencies>
    複製代碼
  2. 下載ChromeDriver並配置環境變量(三選一)翻譯

    2.1 在鏡像站下載ChromeDriver,配置環境變量

    自行手動下載ChromeDriver後如不配置環境變量,需在代碼中加上System.setProperty("webdriver.chrome.driver",path); 其中path是你的driver路徑。

    2.2 Windows使用choco install直接安裝

    2.3 Mac使用brew install cask直接安裝

  3. 編寫Selenium查詞腳本

    3.1 建立Search類,編寫setUp方法 在setUp中,首先須要初始化WebDriver,而後訪問到有道首頁,搜索test點擊肯定並跳轉至搜索頁,注意在driver訪問此頁面時會彈出廣告,須要一行代碼來抓取關閉連接關掉廣告,代碼以下:

    //Direct to YoudaoDic homepage, land in the main search page
     public void setUp() {
         //Go to youdao.com
         driver.get(YOUDAO_HOME_URL);
         driver.manage().window().maximize();
         //Go to the main search page
         driver.findElement(By.id(INPUT_HOME_ID)).sendKeys("test");
         driver.findElement(By.xpath(SEARCH_HOME_XPATH)).click();
         driver.findElement(By.xpath(CLOSE_BTN)).click();
     }
    複製代碼

    3.2 編寫searchWord腳本方法

    searchWord方法須要傳入你要搜索的單詞,而後抓取搜索框,輸入後點擊確認。這時你將得到搜索詳情的頁面,其中你須要抓取中文翻譯的div而且獲取其中文字,代碼以下:

    //Search word and get the translation
     public String searchword(String s) {
         //Find the input element, input the word and click the button
         WebElement input_search = driver.findElement(By.id(INPUT_SEARCH));
         input_search.clear();
         input_search.sendKeys(s);
         driver.findElement(By.xpath(SEARCH_BTN_XPATH)).click();
         //Get the text inside translation div
         String result = driver.findElement(By.className(TRANSLATION_CLASS)).getText();
         return result;
     }
    複製代碼
  4. 讀寫Excel並保存

    4.1 建立Excel文件並寫入單詞

    新建一個Excel,而後在最左邊第一列填入一些單詞,注意,不要有空行,本文代碼中沒有帶異常處理,空行會報錯。

    4.2 編寫Excelio類,編寫read方法

    利用poi框架,與普通文件讀寫殊途同歸,代碼以下:

    public Workbook read(int columnIndex, int count) throws IOException {
        FileInputStream fis = null;
        fis = new FileInputStream(new File(path));
        //Input and save as a xlsx workbook
        Workbook workbook = new XSSFWorkbook(fis);
        fis.close();
        return workbook;
    }
    複製代碼

    4.3 編寫searchWord方法

    調用Search類的searchWord進行搜索,而後將獲取到的String寫入Excel,代碼以下:

    //Search the word and write down
     public void searchWord(Workbook workbook, int columnIndex, int count) {
         //Initialize driver
         WebDriver driver = new ChromeDriver();
         Search search = new Search(driver);
         search.setUp();
         //Search for all words in one column and print to another column
         for (int i = 0; i < count; i++) {
             //Get value of the cell and get the translation through search method
             Sheet sheet = workbook.getSheetAt(0);
             Row row = sheet.getRow(i);
             Cell cell = row.getCell(columnIndex);
             String results = search.searchword(cell.getStringCellValue());
             //Write the translation to another column
             Cell temp = row.createCell(columnIndex+1);
             temp.setCellValue(results);
             //Set the new column as "Wrap Text"
             CellStyle cellStyle = workbook.createCellStyle();
             cellStyle.setWrapText(true);
             temp.setCellStyle(cellStyle);
             sheet.setColumnWidth(1,31*256);
         }
    複製代碼

    4.4 編寫save方法

    使用FileOutputStream,保存Excel,代碼以下:

    //Save the change
     public void save(Workbook workbook) throws IOException {
         FileOutputStream outputStream = new FileOutputStream(path);
         workbook.write(outputStream);
         outputStream.close();
         workbook.close();
     }
    複製代碼
  5. 編寫main方法,運行程序

    編寫入口方法,代碼以下:

//Entrance
    public static void main(String[] args) throws IOException {
        Excelio excelio = new Excelio("src/main/resources/wordlist/test.xlsx");
        Workbook workbook = excelio.read(0, 30);
        excelio.searchWord(workbook,0,30);
        excelio.save(workbook);
    }
複製代碼

結果展現

Excel

過程

結語

本文是爲Selenium的入門而設計,後續做者將在此基礎上,將Selenium結合JavaWeb,更新自動化WebApp的文章,敬請期待。若有疑問歡迎留言交流,歡迎issue和PR,感謝閱讀。

附錄

源碼地址:gitee.com/daniel_ddd/…

相關文章
相關標籤/搜索