java 爬取京东商品详细信息 价格
获取图中的价格,因为京东的价格有反扒机制,价格通过js加载的,直接通过页面标签是获取不到的,所以我们要去要相应的js。
http://p.3.cn/prices/mgets?skuIds=J_
通过发现,这个链接就是查询价格的链接,J_后面跟的就是商品的id,京东商品的id很好找,就是链接中的id:
代码实现
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.2</version>
</dependency>
public static String sendGet(String url, String param) {
String result = "";
String urlName = url + "?" + param;
try {
URL realURL = new URL(urlName);
URLConnection conn = realURL.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) throws Exception {
String url = "https://item.jd.com/65590733400.html";
String skuId = Pattern.compile("[^0-9]").matcher(url).replaceAll("").trim();
String sendRecvGet =sendGet("http://p.3.cn/prices/get","skuid="+skuId);
JSONArray dataArray = new JSONArray(sendRecvGet.toString());
JSONObject dataJsonObj = dataArray.getJSONObject(0);
//提取价格
Object priceStr = dataJsonObj.get("p");
System.out.println("价格:"+priceStr);
}
sendGet方法主要是为了防止爬取的时候被京东给拦截,所以用这个方法模拟浏览器发送get请求。
结果
其他信息比如名称、分类、品牌、图片等就很简单了,直接从页面通过相应的标签获取就行了。