首要要引入jsoup的jar包,这里是在maven项目中的pom文件中引入的依赖。
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.2</version>
</dependency>
package com.zybank.spring.json;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.zybank.spring.gson.framework.GsonTest6;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
* @author:zhangfd
* @version 1.0.0
* @date 2018年12月12日 下午5:02:53
* @description
*/
public class JsonTest1 {
public static void main(String[] args) throws Exception {
String keyword = "手机";
String psort = "3" ; //1-价格 高到底;2-价格 底到高,3-销量 高到底 4-评论数 高到底 5-新品
String serachUrl = "https://search.jd.com/Search?keyword="+keyword+"&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&cid2=653&cid3=655&click=0";
if(null != psort && psort.length() >0)
serachUrl = serachUrl +"&psort="+psort;
List<String> productList= getProductList(serachUrl);
}
public static List<String> getProductList(String serachUrl) throws IOException{
//连接网页,查询这个网页的全部信息
Document doc = Jsoup.connect(serachUrl).get();
//解析网页,找到div 里id=J_goodsList的内容
Elements el = doc.select("div[id=J_goodsList]");
Elements urls = el.select("li[class=gl-item]");
List<String> productList = new ArrayList<String>();
for(Element e:urls){
Attributes attr= e.attributes();
productList.add(attr.get("data-sku"));
}
return productList;
}
}