Java零基础入门——使用jsoup进行初级网络爬虫

2024-04-01 07:38

本文主要是介绍Java零基础入门——使用jsoup进行初级网络爬虫,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

      • 0. 配置jsoup
      • 1. 实战爬虫知乎
      • 2. 实战汽车之家爬图

0. 配置jsoup

  • 安装idea并打开创建class
  1. 打开idea,File->New->Project->Maven->Next----->Finish
  2. 在文件夹src->main->java下先创建package,再在该package下创建java class。
  • 配置jsoup
    把以下的文档复制粘贴到pom.xml:
<dependencies><dependency><!-- jsoup HTML parser library @ http://jsoup.org/ --><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.10.2</version></dependency></dependencies>

1. 实战爬虫知乎

先使用jsoup获取网页的源代码,具体的,可以用Chrome浏览器打开该网页,右击查看源代码。

Document document=Jsoup.connect("https://www.zhihu.com/explore/recommendations")
.userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)")
.get();

注:userAgent需要在网页中找对应的,具体的地方在:
在这里插入图片描述
然后是找到url,具体也是通过网页的源代码中去找(其实,爬虫爬虫,爬的就是网页,所以所有的去网页的源代码中去找就对了),先贴源码:

Element main = document.getElementById("zh-recommend-list-full");
Elements url = main.select("div").select("h2").select("a[class=question_link]");

注: 其中,document.getElementById表示通过id定位到你要爬取的块,然后用.select定位到前缀包含这些限定词的所有url

对应网页的源代码部分:
在这里插入图片描述
在这里插入图片描述
然后去遍历获取到的所有url

for(Element question:url)

并解析出单个问题的URL并连接,方式如上所述:

String URL=question.attr("abs:href");
Document document2=Jsoup.connect(URL).userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36").get();

然后同样的方式获取问题、问题描述、回答:

//问题
Elements title=document2.select(".QuestionHeader-main").select(".QuestionHeader-title");
//问题描述
Elements detail=document2.select(".QuestionHeader-detail").select(".QuestionRichText").select("span[class=RichText ztext]span[itemprop=text]");
//回答
Elements answer=document2.select(".RichContent").select(".RichContent-inner").select("span[class=RichText ztext CopyrightRichText-richText]span[itemprop=text]");

在这里插入图片描述
最后打印出来就好了,以下是完整代码:

package spider;import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;public class spider {public static void main(String[] args) throws IOException {//获取编辑推荐页Document document=Jsoup.connect("https://www.zhihu.com/explore/recommendations")//模拟火狐浏览器.userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)").get();Element main=document.getElementById("zh-recommend-list-full");//System.out.println(main);Elements url=main.select("div").select("h2").select("a[class=question_link]");for(Element question:url){//输出href后的值,即主页上每个关注问题的链接String URL=question.attr("abs:href");//下载问题链接指向的页面Document document2=Jsoup.connect(URL).userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36").get();//问题
//            Elements title=document2.select("#zh-question-title").select("h2").select("a");Elements title=document2.select(".QuestionHeader-main").select(".QuestionHeader-title");//问题描述Elements detail=document2.select(".QuestionHeader-detail").select(".QuestionRichText").select("span[class=RichText ztext]span[itemprop=text]");//回答Elements answer=document2.select(".RichContent").select(".RichContent-inner").select("span[class=RichText ztext CopyrightRichText-richText]span[itemprop=text]");if(detail.size() == 0){System.out.println("\n"+"链接:"+URL+"\n"+"标题:"+title.text()+"\n"+"问题描述:"+"无"+"\n"+"回答:"+answer.text());}else{System.out.println("\n"+"链接:"+URL+"\n"+"标题:"+title.text()+"\n"+"问题描述:"+detail.text()+"\n"+"回答:"+answer.text());}}}
}

结果截图:
在这里插入图片描述
参考:https://blog.csdn.net/u014798883/article/details/54909951(原代码跑不通,本博文有改)

2. 实战汽车之家爬图

还是同样的思路,只不过这里是获取图片的URL,然后下载图片就好了,这里下载图片的代码是copy别人的,原代码忘了网址,发现的朋友请告知一声,我贴上链接或者删掉,谢谢理解-。

这里就直接贴源码了:

package spider;import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;import java.io.IOException;import java.io.File;
import java.io.IOException;import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;public class spider_picture {private static void downImages(String filePath, String imgUrl) {// 若指定文件夹没有,则先创建File dir = new File(filePath);if (!dir.exists()) {dir.mkdirs();}// 截取图片文件名String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1, imgUrl.length());try {// 文件名里面可能有中文或者空格,所以这里要进行处理。但空格又会被URLEncoder转义为加号String urlTail = URLEncoder.encode(fileName, "UTF-8");// 因此要将加号转化为UTF-8格式的%20imgUrl = imgUrl.substring(0, imgUrl.lastIndexOf('/') + 1)+ urlTail.replaceAll("\\+", "\\%20");} catch (UnsupportedEncodingException e) {e.printStackTrace();}// 写出的路径File file = new File(filePath + File.separator + fileName);try {// 获取图片URLURL url = new URL(imgUrl);// 获得连接URLConnection connection = url.openConnection();// 设置10秒的相应时间connection.setConnectTimeout(10 * 1000);// 获得输入流InputStream in = connection.getInputStream();// 获得输出流BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));// 构建缓冲区byte[] buf = new byte[1024];int size;// 写入到文件while (-1 != (size = in.read(buf))) {out.write(buf, 0, size);}out.close();in.close();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) throws IOException {//获取图片爬虫页Document document = Jsoup.connect("https://car.autohome.com.cn/photolist/series/34231/4457966.html#pvareaid=3454450").userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36").get();String id = "pa";int n = 1;while (n < 4) {Element main=document.getElementById("pa" + n);Elements url = main.select("li").select("img");for(Element picture:url) {//输出href后的值,即主页上每个关注问题的链接String URL=picture.attr("abs:src");System.out.println(URL);downImages("d:/this_is_save_pictures_folder", URL);}n += 1;}}
}

这篇关于Java零基础入门——使用jsoup进行初级网络爬虫的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/866590

相关文章

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.