最近打算换房子,豆瓣上面的租房小组相对来说较为真实,但是发现搜索功能不是那么友好,所以想把帖子的数据都爬到数据库,自己写sql语句去筛选,开搞!
每步过程都贴上完整代码,感兴趣的可以看下过程,没时间的同学直接拉到最下复制最终的代码去试试看也OK。
一、获取每页的url
首先分析URL的规律。
链接:龙岗租房小组
第一页:
第二页:
很容易发现参数 start 代表的是每页帖子条数的开始,每页显示25行。我们就可以同过这个参数,写一个循环,每次增加25来获取每一页的内容。
注意:循环内需要try捕捉异常,这里设置的连接超时时间为10秒,如果因为网络的原因超时,会抛出异常,中断循环。使用try块后顶多这一页的数据不要了。如果想完整的收集数据,可以在catch块让 pageStrat - 25 然后进入下个循环再次访问这页。
package douban;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
public class Main2 {
public static String DOU_BAN_URL = "https://www.douban.com/group/longgangzufang/discussion?start={pageStart}";
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException, InterruptedException {
int pageStrat = 0;
while(true) {
try {
URL url = new URL(DOU_BAN_URL.replace("{pageStart}",pageStrat+""));
System.out.println("当前页面:" + DOU_BAN_URL.replace("{pageStart}",pageStrat+""));
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//设置请求方式
connection.setRequestMethod("GET");
// 10秒超时
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
//连接
connection.connect();
//得到响应码
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
//得到响应流
InputStream inputStream = connection.getInputStream();
//获取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String returnStr = "";
String line;
while ((line = reader.readLine()) != null){
returnStr+=line + "\r\n";
}
//该干的都干完了,记得把连接断了
reader.close();
inputStream.close();
connection.disconnect();
System.out.println(returnStr);
}
}catch(Exception e) {
e.printStackTrace();
}
pageStrat+=25;
}
}
}
运行程序,能得到每一页的整个html,存在变量 returnStr 中。
二、从每页的html中取得帖子详情的url
接下来需要分析每个帖子详情的url,利用正则表达式提取
这里用到的是这两个类
import java.util.regex.Matcher;
import java.util.regex.Pattern;
正则表达式这块就自己去学把。下面贴出获取到匹配到url的代码。
package douban;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main2 {
public static String DOU_BAN_URL = "https://www.douban.com/group/longgangzufang