python爬虫
前言
某个夜深人静的夜晚,夜微凉风微扬,月光照进我的书房~
当我打开文件夹以回顾往事之余,惊现许多看似杂乱的无聊代码。我拍腿正坐,一个想法油然而生:“生活已然很无聊,不如再无聊些叭”。
于是,我决定开一个专题,便称之为无敌浪子的无聊小发明。 妙…啊~~~
一、代码分析
前几天实验室中貌美如花的老师问我可以做爬虫嘛,凭借大学学过爬虫一点皮毛要说会哦, 于是凭借本人精通java开发,利用java语言便可轻松地对网页数据进行爬取并处理。
一、首先定义相关网页配置文件
// 设置指定键对值的系统属性
System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe");
// 创建无Chrome无头参数
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("-headless");
WebDriver driver = new ChromeDriver();
// driver.get("http://www.dianping.com/ruzhou/ch10");
// 窗口最大化
// driver.manage().window().maximize();
driver.get("网址url");
// 初始化 不加载图片
// 设置超时5秒 默认也有的可能长一点。
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
boolean loadcomplete = d.findElement(By.tagName("body")).isDisplayed();
return loadcomplete;
}
});
二、开启爬虫之路
Document doc = Jsoup.parse(driver.getPageSource());
// Elements container = doc.select("div.td_div");
Elements container = doc.select("div.bet-main bet-main-dg");
// System.out.println(container.html());
Elements table = container.select("table#MatchTable.socai");
// System.out.println(table.html());
Elements tr_ri_dates = table.get(0).select("tr.ttis");
// 拿所有的兄弟节点
List<Element> next_all = tr_ri_dates.get(0).siblingElements();
// System.out.println(next_all.size());
int i = 1;
// 遍历所有节点
String title_id = "";
List<String> id_list = new ArrayList<String>();// 拿到所有的id
for (Element element : next_all) {
// 没有id的是 class="niDate"
// id row_3390001 row 是标题
// id tr_3390001 tr的是详情内容
String id_str = element.attr("id");
// System.out.println(i+":"+id_str);
if (id_str.indexOf("row") != -1) {
// 这是标题 记录标题id
title_id = id_str.substring(4, id_str.length());
// System.out.println(title_id);
id_list.add(title_id.trim());
}
i++;
}
// 把数据进行分组
List<JSONObject> dataList = new ArrayList<JSONObject>();
for (String id : id_list) {
dataList.add(jiexi(id, next_all));
}
createExcel(dataList);
driver.close();
driver.quit();
}
三、对爬取的数据进行插入execl操作
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setColor(Font.COLOR_RED);
style.setFont(font);
Row row1 = sheet.createRow(((i - 1) * 32) + 1);
Cell cell1 = row1.createCell(0);
cell1.setCellStyle(style);
cell1.setCellValue(obj.getString("bianhao"));
Row row2 = sheet.createRow(((i - 1) * 32) + 2);
Cell cell2 = row2.createCell(0);
cell2.setCellStyle(style);
cell2.setCellValue(obj.getString("bianhao") + "的胜负平");
Row row3 = sheet.createRow(((i - 1) * 32) + 3);
row3.createCell(0).setCellValue("第1场" + obj.getString("zhou") + obj.getString("bianhao") + " 胜平负");
Row row4 = sheet.createRow(((i - 1) * 32) + 4);
row4.createCell(0).setCellValue(obj.getString("vs"));
Row row5 = sheet.createRow(((i - 1) * 32) + 5);
row5.createCell(0).setCellValue(obj.getString("s") + "元");
运行效果如下:
啦啦啦,无敌浪子的完美之作,是不是很酷哈哈哈!!!
写在最后
交给貌美如花的大师姐哈皮,是不是很调皮,更亲近喽哈哈哈。
最后,感谢各位大大的耐心阅读,咋们下次再会~
创作不易,大侠请留步… 动起可爱的双手,来个赞再走呗 (๑◕ܫ←๑)