package seleniumLearn1;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import com.gargoylesoftware.htmlunit.javascript.host.Element;
/**
* 獲取http://www.qyer.com頁面中,所有</a>標簽"href"屬性值
* 包含英文單詞“place”的URL,並將結果保存到“/home/result.log”文件中。
* @author 0
*
*/
public class Search {
static String baseUrl="http://www.qyer.com";
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "E:\\\\webDriver\\\\chromedriverV2.28.exe");
File logFile = new File("d://logFile.txt");
if(!(logFile.exists())) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
WebDriver driver = new ChromeDriver();
driver.get(baseUrl);
//獲取所有a標簽
List<WebElement> aList = driver.findElements(By.tagName("a"));
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
//便利所有標簽
FileOutputStream fs = null;
try {
fs = new FileOutputStream(logFile);
for (WebElement a : aList) {
System.out.println(a.getAttribute("href"));//獲取a標簽中的URL
//獲取a標簽href屬性值
String urlStr = a.getAttribute("href");
if(urlStr.contains("place")) {
urlStr +="\r\n";
//將URL寫入文件中
fs.write(urlStr.getBytes());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}