CrawlUtils.java 9.63 KB
package com.bs.cardata.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bs.cardata.constant.ServiceConstants;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class CrawlUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(CrawlUtils.class);

	public static Elements getBaseElements(String url, String tag, Integer type) {
		Elements res = null;
		try {
			Document doc = Jsoup.connect(url).get();
			// type:1 divTag;2 className
			if (type.intValue() == 1) {
				res = doc.getElementsByTag(tag);
			} else if (type.intValue() == 2) {
				res = doc.getElementsByAttributeValue("class", tag);
			} else if (type.intValue() == 3) {
				res = doc.getElementsByAttributeValue("id", tag);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return res;
	}

	public static Document getBaseDoc(String url) {
		Document doc = null;
		try {
			doc = Jsoup.connect(url).get();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return doc;
	}

	public static Elements getElementsForDoc(Document rootDoc, String tag, int type) {
		Elements res = null;
		try {
			// type:1 divTag;2 className
			if (type == 1) {
				res = rootDoc.getElementsByTag(tag);
			} else if (type == 2) {
				res = rootDoc.getElementsByAttributeValue("class", tag);
			} else if (type == 3) {
				res = rootDoc.getElementsByAttributeValue("id", tag);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return res;
	}

	public static JSONObject getDealerPriceJson(Elements elmes) {
		JSONObject res = new JSONObject();
		Elements idElemes = elmes.get(0).getElementsByAttributeValue("class", "interval01-list-cars");
		String ids = "";
		for (Element ele : idElemes) {
			if (ele.getElementsByTag("p").size() > 0 && ele.getElementsByTag("p").get(0).attr("data-gcjid") != null && !StringUtils.isEmpty(ele.getElementsByTag("p").get(0).attr("data-gcjid"))) {
				ids = ids + ele.getElementsByTag("p").get(0).attr("data-gcjid") + ",";
			}
		}
		ids = ids.substring(0,ids.length()-1);
		String postRes = HttpUtil.get("http://dealer.api.autohome.com.cn/dealerrest/price/GetMinPriceBySpecSimple?_appId=cms&cityid=440300&SpecIds="+ids+"&_callback=DealerBySpec");
		JSONObject resJson = JSONObject.parseObject(postRes.replace("DealerBySpec(", "").replace(")", ""));
        JSONArray listJson = resJson.getJSONObject("result").getJSONArray("list");
		Iterator<Object> it = listJson.iterator();
		while (it.hasNext()) {
			JSONObject json = (JSONObject) it.next();
			res.put(json.getString("MinPrice"), json);
		}
		
		return res;
	}

	public static String getCarTypeDetailInfo(String specId, String seriesId) {
		JSONObject resJson = new JSONObject();
		String url = ServiceConstants.TYPE_DETAIL_URL.replace("[SPECID]", specId).replace("[SERIESID]", seriesId);
		Elements elmes = getBaseElements(url, "tabcont-cont", 2);
		if (elmes != null && !elmes.isEmpty()) {
			Elements baseDiv10 = elmes.get(0).getElementsByAttributeValue("id", "tab-10");
			if (baseDiv10 != null && !baseDiv10.isEmpty()) {
				resJson = getCarTypeForTab(resJson, baseDiv10);
			}
			Elements baseDiv11 = elmes.get(0).getElementsByAttributeValue("id", "tab-11");
			if (baseDiv11 != null && !baseDiv11.isEmpty()) {
				resJson = getCarTypeForTab(resJson, baseDiv11);
			}
		}
		return resJson.toString();
	}

	private static JSONObject getCarTypeForTab(JSONObject resJson, Elements baseDiv) {
		Elements titleElmes = baseDiv.get(0).getElementsByAttributeValue("class", "config-title");
		Elements configElmes = baseDiv.get(0).getElementsByAttributeValue("class", "config-table");
		for (int i = 0; i < titleElmes.size(); i++) {
			String titleName = titleElmes.get(i).text();
			JSONObject trJson = new JSONObject();
			Elements trElmes = configElmes.get(i).getElementsByTag("tr");
			for (Element trEle : trElmes) {
				Elements thElmes = trEle.getElementsByTag("th");
				Elements tdElmes = trEle.getElementsByTag("td");
				for (int j = 0; j < thElmes.size(); j++) {
					String key = thElmes.get(j).text();
					String value = tdElmes.get(j).text();
					if (!StringUtils.isEmpty(key) && !"-".equals(key)) {
						trJson.put(key, value);
					}
				}
			}
			resJson.put(titleName, trJson.toString());
		}
		return resJson;
	}

	public static JSONObject getDealerRestPrice(String specId) {
		JSONObject res = new JSONObject();

		String guidPrice = "暂无";
		String lowerPrice = "暂无";

		JSONArray listJson = null;
		try {
			String postRes = HttpUtil.get("http://dealer.api.autohome.com.cn/dealerrest/price/GetMinPriceBySpecSimple?_appId=cms&cityid=440300&SpecIds=" + specId + "&_callback=DealerBySpec");
			JSONObject resJson = JSONObject.parseObject(postRes.replace("DealerBySpec(", "").replace(")", "").replace(";", "").replace("/**/", ""));
			listJson = resJson.getJSONObject("result").getJSONArray("list");
		} catch (Exception e) {
			LOGGER.error("车型:specId" + specId + "获取经销商价格异常" + e.getMessage(), e);
		}

		if (listJson!=null && !listJson.isEmpty()) {
			JSONObject baseJson = listJson.getJSONObject(0);
			try {
				double guidPriceNum = (double) baseJson.getIntValue("MinOriginalPrice") / 10000;
				guidPrice = String.valueOf(guidPriceNum);
			} catch (Exception e) {
			}
			try {
				double lowerPriceNum = (double) baseJson.getIntValue("MinPrice") / 10000;
				lowerPrice = String.valueOf(lowerPriceNum);
			} catch (Exception e) {
			}
		}
		res.put("guidPrice", guidPrice);
		res.put("lowerPrice", lowerPrice);
		return res;
	}

	public static String getCarTypeDetailInfoNew(String serverUrl, String specId, String seriesId) {
		JSONObject resJson = new JSONObject();
		// https://www.autohome.com.cn/web-main/car/param/getParamConf?mode=1&site=2&specid=76430
		// String specParamUrl = PropertyConfigurer.getString("autohome.cartype.params.config.url");
		String url = serverUrl + "&specid=" + specId;

		try {
			String jsonRes = HttpUtil.get(url);
			if (StringUtils.isEmpty(jsonRes)) {
				LOGGER.info("====Get_car_type_config_error==data empty==" + url);
				return resJson.toString();
			}

			JSONObject response = JSONObject.parseObject(jsonRes);
			if (response.getIntValue("returncode") != 0) {
				LOGGER.info("====Get_car_type_config_error====returncode is:" + response.getIntValue("returncode"));
				return resJson.toString();
			}

			JSONObject result = response.getJSONObject("result");

			// 1. 解析titlelist,构建 itemtype -> JSONObject 的映射
			JSONArray titleList = result.getJSONArray("titlelist");
			// key: itemtype(如"基本参数"、"发动机"),value: 该分组下的参数JSONObject
			Map<String, JSONObject> typeItemsMap = new HashMap<>();
			// key: titleid,value: 所属分组的 itemtype
			Map<Integer, String> titleIdToTypeMap = new HashMap<>();
			// key: itemtype,value: titleid -> itemname 的映射
			Map<String, Map<Integer, String>> typeTitleItemMap = new HashMap<>();

			for (int i = 0; i < titleList.size(); i++) {
				JSONObject titleGroup = titleList.getJSONObject(i);
				String itemType = titleGroup.getString("itemtype");

				if (!"基本参数".equals(itemType) && !"发动机".equals(itemType)) {
					continue;
				}

				JSONArray items = titleGroup.getJSONArray("items");
				JSONObject itemObj = new JSONObject();
				Map<Integer, String> titleItemMap = new HashMap<>();

				for (int j = 0; j < items.size(); j++) {
					JSONObject item = items.getJSONObject(j);
					int titleId = item.getIntValue("titleid");
					String itemName = item.getString("itemname");
					titleIdToTypeMap.put(titleId, itemType);
					titleItemMap.put(titleId, itemName);
				}

				typeItemsMap.put(itemType, itemObj);
				typeTitleItemMap.put(itemType, titleItemMap);
			}

			// 2. 解析datalist,根据specId匹配并提取paramconflist数据
			JSONArray dataList = result.getJSONArray("datalist");
			for (int i = 0; i < dataList.size(); i++) {
				JSONObject dataItem = dataList.getJSONObject(i);
				if (!specId.equals(dataItem.getString("specid"))) {
					continue;
				}

				JSONArray paramConfList = dataItem.getJSONArray("paramconflist");
				for (int j = 0; j < paramConfList.size(); j++) {
					JSONObject paramConf = paramConfList.getJSONObject(j);
					int titleId = paramConf.getIntValue("titleid");

					String itemType = titleIdToTypeMap.get(titleId);
					if (itemType == null) {
						continue;
					}

					Map<Integer, String> titleItemMap = typeTitleItemMap.get(itemType);
					String itemName = titleItemMap.get(titleId);
					if (itemName == null || itemName.isEmpty()) {
						continue;
					}

					// 获取值:优先取itemname,若有sublist则拼接子项
					String value = paramConf.getString("itemname");
					if (value == null) {
						value = "";
					}
					JSONArray subList = paramConf.getJSONArray("sublist");
					if (subList != null && !subList.isEmpty() && value.isEmpty()) {
						StringBuilder sb = new StringBuilder();
						for (int k = 0; k < subList.size(); k++) {
							JSONObject sub = subList.getJSONObject(k);
							if (k > 0) {
								sb.append("/");
							}
							sb.append(sub.getString("name"));
						}
						value = sb.toString();
					}

					JSONObject itemObj = typeItemsMap.get(itemType);
					itemObj.put(itemName, value);
				}
				break;
			}

			// 3. 将解析结果放入resJson
			for (Map.Entry<String, JSONObject> entry : typeItemsMap.entrySet()) {
				resJson.put(entry.getKey(), entry.getValue());
			}

		} catch (Exception e) {
			LOGGER.error("====Get_car_type_config_exception====" + e.getMessage(), e);
		}

		return resJson.toString();
	}

}