package com.yiwoqu.yiwoquesjd.utils;
import com.yiwoqu.yiwoquesjd.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import java.net.URL;
import java.util.ArrayList;
/**
* @ClassName: HtmlParesUtil
* @Description: 爬取京东数据
* @author: 易海涛
* @date: 2020/8/24 10:34
*/
@Component
//HTME解析工具
public class HtmlParseUtil {
public static void main(String[] args) throws Exception {
new HtmlParseUtil().parseJD("java").forEach(System.out::println);
}
public ArrayList<Content> parseJD(String kewwords) throws Exception{
//获取请求
String url = "https://search.jd.com/Search?keyword="+kewwords;
Document document =Jsoup.parse(new URL(url),30000);
Element element = document.getElementById("J_goodsList");
Elements elements= element.getElementsByTag("li");
ArrayList<Content> goodsList = new ArrayList<>();
for (Element el : elements){
String img = el.getElementsByTag("img").eq(0).attr("src");
String price = el.getElementsByClass("p-price").eq(0).text();
String title = el.getElementsByClass("p-name").eq(0).text();
Content content = new Content();
content.setImg(img);
content.setPrice(price);
content.setTitle(title);
goodsList.add(content);
}
return goodsList;
}
}
Java爬取京东商品
最新推荐文章于 2024-08-22 22:09:54 发布