一.selenium
1.介绍Selenium
Selenium是一个用于Web应用程序自动化测试工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。
主要功能包括:测试与浏览器的兼容性——测试你的应用程序看是否能够很好得工作在不同浏览器和操作系统之上。
测试系统功能——创建回归测试检验软件功能和用户需求。支持自动录制动作和自动生成 .Net、Java、Perl等不同语言的测试脚本。
2.下载chromedriver驱动
下载地址:http://npm.taobao.org/mirrors/chromedriver/
选择跟自己的Google浏览器Chrome版本一致的驱动程序(chrome浏览器版本可以通过点击帮助,再点击关于Google Chrome中查看),然后放在自己电脑谷歌浏览器的安装程序目录下,如果是默认安装的话,目录应该是C:\Program Files (x86)\Google\Chrome\Application。(提示:放置的时候,如果杀毒软件禁止,可以先把杀毒软件关一下。)
3.环境变量配置
在path中加入C:\Program Files (x86)\Google\Chrome\Application
环境变量.png
4.selenium依赖包
我是从csdn上下载的,下载地址为:https://download.csdn.net/download/ajaxhu/8919691
不过也可以自己去maven repository网站上通过maven依赖下载,主要网络不好,所以直接从csdn下了,打包时会有问题,需要把gson改成下面2.6.2版本,不要用csdn的2.3版本,还有selenium-chrome-driver 2.44.0驱动自己maven引入好了,不然这两个问题会导致打包时报错。然后解析网页代码用的是jsoup的1.11.1版本(maven依赖如下)
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>2.44.0</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.1</version>
</dependency>
jsoup的使用文档地址如下:https://www.open-open.com/jsoup/
二.爬虫代码部分
爬取的是https://www.aqistudy.cn/historydata的天气情况网站
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @program: reptile
* @description:
* @author: wuyinhao
* @create:2019-13-13:09
**/
public class RepileUtil {
public static List<String[]> getWeatherDataList(String url, String params){
System.getProperties().setProperty("webdriver.chrome.driver","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
//开启webDriver进程
WebDriver webDriver = new ChromeDriver();
webDriver.get(url+params);
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Document document = Jsoup.parse(webDriver.getPageSource());
Element element = document.getElementsByClass("table table-condensed table-bordered table-striped table-hover table-responsive").first();
List<Element> trList = element.select("tr");
//System.out.println(trList);
List<String[]> list = new ArrayList<>();
for (Element elementTr : trList){
String[] dataList=elementTr.text().split(" ");
for (String data:dataList){
System.out.print(data + " ");
}
list.add(dataList);
}
webDriver.close();
//webDriver.quit();
return list;
}
public static void main(String[] args) throws IOException {
List<String[]> list = getWeatherDataList("https://www.aqistudy.cn/historydata/monthdata.php?", "city=北京");
}
}
运行结果如下:
打开北京市的天气情况,然后控制台输出北京天气的历史数据
image.png
image.png
三.将数据导入到excel里面
添加maven依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
代码部分:
public class ExcelUtil {
private static final String EXCEL_XLS = "xls";
private static final String EXCEL_XLSX = "xlsx";
public static List<String[]> readExcel(int cloumnCount, String finalXlsxPath, boolean isHasFirstRow) throws FileNotFoundException {
File file = new File(finalXlsxPath);
FileInputStream fis;
fis = new FileInputStream(file);
List<String[]> resultList = new ArrayList<>();
try {
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fis);
for (int numSheet = 0;numSheet < 1; numSheet++){ //xssfWorkbook.getNumberOfFonts()
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
if (xssfSheet == null) {
continue;
}
System.out.println(xssfSheet.getLastRowNum());
for (int numRow=isHasFirstRow?0:1;numRow<=xssfSheet.getLastRowNum();numRow++){
XSSFRow xssfRow = xssfSheet.getRow(numRow);
if (xssfRow!=null){
String[] strs = new String[cloumnCount];
for (int numCol=0;numCol<cloumnCount;numCol++){
XSSFCell xssfCell = xssfRow.getCell(numCol);
strs[numCol] = xssfCell.getStringCellValue();
}
resultList.add(strs);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return resultList;
}
public static void writeExcel(List<String[]> dataList, int cloumnCount, String finalXlsxPath){
OutputStream out = null;
try {
// 获取总列数
int columnNumCount = cloumnCount;
// 读取Excel文档
File finalXlsxFile = new File(finalXlsxPath);
Workbook workBook = getWorkbok(finalXlsxFile);
// sheet 对应一个工作页
Sheet sheet = workBook.getSheetAt(0);
/**
* 删除原有数据,除了属性列
*/
int rowNumber = sheet.getLastRowNum(); // 第一行从0开始算
System.out.println("原始数据总行数,除属性列:" + rowNumber);
for (int i = 1; i <= rowNumber; i++) {
Row row = sheet.getRow(i);
sheet.removeRow(row);
}
// 创建文件输出流,输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效
out = new FileOutputStream(finalXlsxPath);
workBook.write(out);
out.close();
/**
* 往Excel中写新数据
*/
for (int j = 0; j < dataList.size(); j++) {
// 创建一行:从第二行开始,跳过属性列
Row row = sheet.createRow(j);
// 得到要插入的每一条记录
String[] strArr = dataList.get(j);
//String name = dataMap.get("BankName").toString();
//String address = dataMap.get("Addr").toString();
//String phone = dataMap.get("Phone").toString();
for (int k = 0; k < columnNumCount; k++) {
// 在一行内循环
Cell cell = row.createCell(k);
cell.setCellValue(strArr[k]);
}
}
// 创建文件输出流,准备输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效
out = new FileOutputStream(finalXlsxPath);
workBook.write(out);
workBook.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(out != null){
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("数据导出成功");
}
public static Workbook getWorkbok(File file) throws IOException{
Workbook wb = null;
FileInputStream in = new FileInputStream(file);
if(file.getName().endsWith(EXCEL_XLS)){ //Excel 2003
wb = new HSSFWorkbook(in);
}else if(file.getName().endsWith(EXCEL_XLSX)){ // Excel 2007/2010
wb = new XSSFWorkbook(in);
}
return wb;
}
private static int getRandom(int count) {
return (int) Math.round(Math.random() * (count));
}
private static String string = "abcdefghijklmnopqrstuvwxyz";
private static String getRandomString(int length) {
StringBuffer sb = new StringBuffer();
int len = string.length();
for (int i = 0; i < length; i++) {
sb.append(string.charAt(getRandom(len - 1)));
}
return sb.toString();
}
public static String getExcelPath() throws IOException {
String filePath = getRandomString(10) + ".xlsx";
Workbook wb = new XSSFWorkbook();
wb.createSheet();
FileOutputStream fileOut = new FileOutputStream( filePath);
wb.write(fileOut);
fileOut.close();
return filePath;
}
}
然后重新编写main函数进行测试
public static void main(String[] args) throws IOException {
List<String[]> list = RepileUtil.getWeatherDataList("https://www.aqistudy.cn/historydata/monthdata.php?", "city=北京");
ExcelUtil.writeExcel(list, 10, ExcelUtil.getExcelPath());
// for (String[] strList:list){
// for (String str:strList){
// System.out.print(str + " ");
// }
// System.out.println();
// }
}
image.png
然后可以去项目目录下找到生成的excel文件
image.png四.补充版(Firefox火狐浏览器版本)
1.maven依赖
只需要添加这两个依赖jar包,上面的就不用了
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.1</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.4.0</version>
</dependency>
2.火狐浏览器驱动下载地址:
下载的驱动版本需要跟火狐浏览器一致
https://github.com/mozilla/geckodriver/releases/
3.启动
System.setProperty("webdriver.firefox.bin", firefoxPath); //firefoxPath为火狐浏览器的启动程序的路径,例如:C:\Program Files\Mozilla Firefox\firefox.exe
System.setProperty("webdriver.gecko.driver", firefoxdriverPath); //firefoxdriverPath是Firefox驱动的路径,例如:D:\firefox_driver\geckodriver.exe
webDriver = new FirefoxDriver();
剩下就使用jsoup解析,同上面chrome的使用一样
网友评论