1 public void execute(string username) { 2 // 获取cookie 3 string cookie = getcookie(username); 4 // 获取首页html内容 5 string content = http.get("http://tieba.baidu.com/mo/", cookie); 6 // 获取所有连接 7 string links = getmore(content); 8 links = "http://tieba.baidu.com" + links; 9 // 获取所有贴吧html内容 10 content = http.get(links, cookie); 11 list<string> likeslink = getlike(content); 12 sign(likeslink, cookie, username); 13 }
我们用第三方工具包 httpclientutil 可以直接发送get请求(已经封装好的)
2.清理数据:
1 private void sign(list<string> likeslink, string cookie, string username) { 2 for (string link : likeslink) { 3 string content = http.get(link, cookie); 4 document doc = jsoup.parse(content); 5 elements titles = doc.getelementsbyclass("bc"); 6 string title = titles.get(0).text(); 7 title = title.split("吧")[0]; 8 elements links = doc.select("a[href]"); 9 boolean flag = true; 10 for (element ele : links) { 11 string ss = ele.attr("href"); 12 ss = "http://tieba.baidu.com" + ss; 13 if (ss.contains("sign")) { 14 http.get(ss, cookie); 15 // 插入到数据库中 16 string date = new simpledateformat("yyyy-mm-dd hh:mm:ss.sss").format(new date()); 17 dao.insertrecord(username, title, date, "签到成功"); 18 flag = false; 19 break; 20 } 21 } 22 if (flag) { 23 // 插入到数据库中 24 string date = new simpledateformat("yyyy-mm-dd hh:mm:ss.sss").format(new date()); 25 dao.insertrecord(username, title, date, "已签到"); 26 } 27 } 28 }
我们这里用的第三方工具 jsoup, jsoup可以像dom一样简单的获取任何东西。甚至你可以用这个则来进行获取。
项目源码:贴吧一键签到
项目地址:
1 public list<string> getcontent() { 2 3 list<string> res = new arraylist<>(); 4 // 92是固定的,帖子的总数 5 for (int i = 1; i <= 92; i++) { 6 string url = geturl(i); 7 string content = http.get(url); 8 getparse(content, res); 9 } 10 return res; 11 }
1 private void getparse(string content, list<string> res) { 2 3 document doc = jsoup.parse(content); 4 elements links = doc.getelementsbyclass("bd"); 5 for (element link : links) { 6 string str = link.tostring(); 7 pattern pattern = pattern.compile("<p>[.\\s\\s]+?div"); 8 matcher m = pattern.matcher(str); 9 while (m.find()) { 10 string s = m.group(); 11 s = s.replaceall("<", ""); 12 s = s.replaceall(">", ""); 13 s = s.replaceall("/", ""); 14 s = s.replaceall("p", ""); 15 s = s.replaceall("div", ""); 16 s = s.replaceall("\n", ""); 17 res.add(s); 18 } 19 } 20 }
项目源码:
用java做爬虫,无非两点
当我们这两点都会的时候,那么就十分的简单了。当然这里也用到了第三方的开源jar包
ps. 如果你对爬虫也感兴趣,我之前写过一个爬知乎图片的爬虫 前方高能
可以自己爬下来,慢慢欣赏,不用谢我
如对本文有疑问, 点击进行留言回复!!
Spring-Boot快速集成netty-socketio(socket服务实现,支持认证)
网友评论