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

相关文章

如何使用 Python 读取 Excel 数据

《如何使用Python读取Excel数据》:本文主要介绍使用Python读取Excel数据的详细教程,通过pandas和openpyxl,你可以轻松读取Excel文件,并进行各种数据处理操... 目录使用 python 读取 Excel 数据的详细教程1. 安装必要的依赖2. 读取 Excel 文件3. 读

SpringBoot请求参数接收控制指南分享

《SpringBoot请求参数接收控制指南分享》:本文主要介绍SpringBoot请求参数接收控制指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring Boot 请求参数接收控制指南1. 概述2. 有注解时参数接收方式对比3. 无注解时接收参数默认位置

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

SpringBoot项目中报错The field screenShot exceeds its maximum permitted size of 1048576 bytes.的问题及解决

《SpringBoot项目中报错ThefieldscreenShotexceedsitsmaximumpermittedsizeof1048576bytes.的问题及解决》这篇文章... 目录项目场景问题描述原因分析解决方案总结项目场景javascript提示:项目相关背景:项目场景:基于Spring

Spring Boot 整合 SSE的高级实践(Server-Sent Events)

《SpringBoot整合SSE的高级实践(Server-SentEvents)》SSE(Server-SentEvents)是一种基于HTTP协议的单向通信机制,允许服务器向浏览器持续发送实... 目录1、简述2、Spring Boot 中的SSE实现2.1 添加依赖2.2 实现后端接口2.3 配置超时时

解决Maven项目idea找不到本地仓库jar包问题以及使用mvn install:install-file

《解决Maven项目idea找不到本地仓库jar包问题以及使用mvninstall:install-file》:本文主要介绍解决Maven项目idea找不到本地仓库jar包问题以及使用mvnin... 目录Maven项目idea找不到本地仓库jar包以及使用mvn install:install-file基

Spring Boot读取配置文件的五种方式小结

《SpringBoot读取配置文件的五种方式小结》SpringBoot提供了灵活多样的方式来读取配置文件,这篇文章为大家介绍了5种常见的读取方式,文中的示例代码简洁易懂,大家可以根据自己的需要进... 目录1. 配置文件位置与加载顺序2. 读取配置文件的方式汇总方式一:使用 @Value 注解读取配置方式二

一文详解Java异常处理你都了解哪些知识

《一文详解Java异常处理你都了解哪些知识》:本文主要介绍Java异常处理的相关资料,包括异常的分类、捕获和处理异常的语法、常见的异常类型以及自定义异常的实现,文中通过代码介绍的非常详细,需要的朋... 目录前言一、什么是异常二、异常的分类2.1 受检异常2.2 非受检异常三、异常处理的语法3.1 try-

Java中的@SneakyThrows注解用法详解

《Java中的@SneakyThrows注解用法详解》:本文主要介绍Java中的@SneakyThrows注解用法的相关资料,Lombok的@SneakyThrows注解简化了Java方法中的异常... 目录前言一、@SneakyThrows 简介1.1 什么是 Lombok?二、@SneakyThrows

Java中字符串转时间与时间转字符串的操作详解

《Java中字符串转时间与时间转字符串的操作详解》Java的java.time包提供了强大的日期和时间处理功能,通过DateTimeFormatter可以轻松地在日期时间对象和字符串之间进行转换,下面... 目录一、字符串转时间(一)使用预定义格式(二)自定义格式二、时间转字符串(一)使用预定义格式(二)自