爬取数据
导入jar包
<properties> <java.version>1.8</java.version> <elasticsearch.version>7.6.1</elasticsearch.version> </properties> <dependencies> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.10.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies>
新建实体类
@Data @NoArgsConstructor @AllArgsConstructor public class Content { private String title; private String img; private String price; }
编写爬虫工具类
public class HtmlParseUtil { public static void main(String[] args) throws Exception { new HtmlParseUtil().parseDDJJ("包").forEach(System.out::println); } public List<Content> parseDDJJ(String keywords) throws Exception { //爬取url地址 String url = "https://search.xxxx.com/Search?keyword="+keywords; //解析网页,30s内未爬取成功,打印错误 Document document = Jsoup.parse(new URL(url),30000); //获取每一本书籍的id Element element = document.getElementById("DJ_goodsList"); //获取所有的li标签 Elements elements = element.getElementsByTag("li"); ArrayList<Content> goodsList = new ArrayList<>(); //遍历li标签的内容 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.setTitle(title); content.setPrice(price); content.setImg(img); goodsList.add(content); } return goodsList; } }
可以看到内容、图片、价格系数爬取
到此这篇关于SpringBoot中使用Jsoup爬取网站数据的方法的文章就介绍到这了,更多相关SpringBoot Jsoup爬取内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!
- 本文固定链接: https://zxbcw.cn/post/188274/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)