selenium小记

今天在群里看到这样一个笔试题:请使用任何熟悉的面向对象编程语言,编写代码,获取http://www.qyer.com页面中,所有标签"href"属性值包含英文单词“place”的URL,并将结果保存到“/home/result.log”文件中。

     思路:用selenium定位获得所有标签包含“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;

importorg.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumTest {

    staticString baseUrl = "http://www.qyer.com";

    publicstaticvoid main(String args[])

    {

        //创建个log文件

File logFile =newFile("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 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文件:

转自:http://www.cnblogs.com/dreamyu/p/6408017.html

你可能感兴趣的:(selenium小记)