一個selenium筆試題——去哪網首頁獲取符合要求的url並保存


     今天在群里看到這樣一個筆試題:請使用任何熟悉的面向對象編程語言,編寫代碼,獲取http://www.qyer.com頁面中,所有</a>標簽"href"屬性值包含英文單詞“place”的URL,並將結果保存到“/home/result.log”文件中。

     思路:用selenium定位獲得所有</a>標簽包含“href”屬性的元素,然后遍歷,符合要求的就寫入到/home/result.log文件中。

    

package com.testngDemo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumTest {

    static String baseUrl = "http://www.qyer.com";
    public static void main(String args[])
    {
        //創建個log文件
        File logFile = new File("d://logFile.txt");
        if(!logFile.exists())
        {
            try {
                logFile.createNewFile();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        //創建一個webdriver
        WebDriver driver = new FirefoxDriver();
        driver.get(baseUrl);
        
        //設置等待
        try {
            Thread.sleep(10000);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        //獲得所有a標簽
        List<WebElement> aList = driver.findElements(By.tagName("a"));
        try {
            Thread.sleep(10000);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        //遍歷所有標簽 
        FileOutputStream fs = null;
        try {
            fs = new FileOutputStream(logFile);
            for(WebElement a:aList){
                System.out.println(a.getAttribute("href"));
                
                //獲得a標簽href屬性
                String urlStr = a.getAttribute("href");
                if(urlStr.contains("place"))
                {
                    urlStr+="\r\n";
                    //將url寫入文件中
                    fs.write(urlStr.getBytes());
                }
            }
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            try {
                fs.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }    
    }
}

查看下log文件:

------------------------------------------------------時間匆忙,隨便寫了下,有時間再優化,重要的是思路吧----------------------------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM