很多人认为写爬虫必须用专业的爬虫语言python或者nutch之类的,其实java爬虫也能胜任许多工作。今天来说说我接触的第一个java爬虫,Jsoup方式的,值得注意的是JSOUP在对于静态页面的抓取效果很好,然而它只能抓取静态资源,所以如果要抓取动态资源的话,那就得换别的java爬虫,不多说先上代码:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static final String AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36";
public static void main(String[] args) throws Exception {
String startPage="http://list.jd.com/list.html?cat=9987,653,655&page={page}&sort=sort_totalsales15_desc&trans=1&JL=6_0_0&ms=6#J_main";
Document document = Jsoup.connect(startPage).userAgent(AGENT).get();
Element pagesDiv = document.getElementById("J_container");
//获取总页数
Elements pages = pagesDiv.select(".p-skip em b");
String pageCount = pages.get(0).text();
int count = Integer.valueOf(pageCount);
int num =0;
//循环抓取
for (int i = 1; i <= count; i++) {
String beginPage="http://list.jd.com/list.html?cat=9987,653,655&page="+ i + "&sort=sort_totalsales15_desc&trans=1&JL=6_0_0&ms=6#J_main";
Document doc = Jsoup.connect(beginPage).userAgent(AGENT).get();
Elements selects = doc.getElementsByClass("gl-item");
for (Element elementDiv : selects) {
Element select =elementDiv.child(0);
//商品ID
String cId = select.attr("data-sku");
//获取商品价格参数界面
String priceUrl = "https://p.3.cn/prices/mgets?skuIds=J_"+cId;
Document priceDom = Jsoup.connect(priceUrl).ignoreContentType(true).get();
Element pElement = priceDom.getElementsByTag("body").get(0);
String iPrice = pElement.text();
//转换成JSON对象然后取值
JSONArray array = JSONArray.fromObject(iPrice);
JSONObject obj = (JSONObject) array.get(0);
Element pName = select.select(".p-name").get(0);
Elements a = pName.getElementsByTag("a");
String cName = a.get(0).text();
String price = (String) obj.get("p");
String itemUrl = a.attr("href");
System.out.println("商品ID:"+cId);
System.out.println("商品名称:"+cName);
System.out.println("商品价格:"+price);
System.out.println("商品链接:"+itemUrl);
num=num+1;
}
}
System.out.println("一共抓到了"+num+"条商品数据");
}
}
代码分几步走:
第一步:分析需求,确定要去抓取的页面
分析页面每次请求时哪些参数在变化,是否是定值?或者是否有方法获取url中参数变量的值,然后拼接url的方式直接用JSOUP.CONNECT().get()的方式直接获取这个页面的静态资源,当然也可以用HttpClient的方式请求获取页面的资源,然后转换后用JSOUP.parse()的方式解析页面;
第二步:审核元素,确定自己要抓取的数据在页面的确切位置
JSOUP提供了一系列的页面元素定位支持,具体查看API文档,这里就不多说
第三步:提取自己需要的元素
定位到要抓取的数据后,可以通过遍历的方式抓取到所有你需要的数据,至于数据的提取无非就是dom对象的取值问题
这就是Jsoup的简单运用,具体的自己参考API写几个DEMO心里也就有数了,此贴只为自己学到的知识做个备注 ,如有不足欢迎指出,谢谢