[JAVA] Jsoup爬虫(新笔趣网)

2023-10-07 19:50
文章标签 java 爬虫 jsoup 笔趣

本文主要是介绍[JAVA] Jsoup爬虫(新笔趣网),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

对新笔趣网的热门小说的爬取

技术选型:Springboot+jsoup

第一步:导入maven依赖
  <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--需要往数据库插入数据,打开注释即可--><!--<dependency>--><!--<groupId>mysql</groupId>--><!--<artifactId>mysql-connector-java</artifactId>--><!--</dependency>--><!--<dependency>--><!--<groupId>com.alibaba</groupId>--><!--<artifactId>druid-spring-boot-starter</artifactId>--><!--<version>1.1.10</version>--><!--</dependency>--><dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.11.2</version></dependency><!-- https://mvnrepository.com/artifact/net.sourceforge.htmlunit/htmlunit --><dependency><groupId>net.sourceforge.htmlunit</groupId><artifactId>htmlunit</artifactId><version>2.30</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.51</version></dependency></dependencies>
第二步:application.yml
# urls
book:biqu:## 笔趣阁的地址url: http://www.xbiquge.la/
第三步: 核心代码

爬虫接口 interface: CommonPuller 便于扩展

/*** @author zcp* @create 2019/12/17* @since 1.0.0*/
public interface CommonPuller{void pullNews();default Document getHtmlFromUrl(String url, boolean useHtmlUnit) throws Exception{if(!useHtmlUnit){//模拟火狐浏览器return Jsoup.connect(url).userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)").get();}else{WebClient webClient=new WebClient(BrowserVersion.CHROME);//javascriptwebClient.getOptions().setJavaScriptEnabled(true);//csswebClient.getOptions().setCssEnabled(false);//webClient.getOptions().setActiveXNative(false);webClient.getOptions().setThrowExceptionOnScriptError(false);webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);webClient.getOptions().setTimeout(10000);HtmlPage rootPage=null;try {rootPage = webClient.getPage(url);webClient.waitForBackgroundJavaScript(10000);String htmlString = rootPage.asXml();return Jsoup.parse(htmlString);}catch (Exception e){throw  e;}finally {webClient.close();}}}
}

例如要爬取笔趣阁,就创建一个BiQuPuller 实现这个接口,这里没有做插入数据库操作,自己根据情况构建实体类,将爬取到的内容封装进实体类,存入数据库

/*** @author zcp* @create 2019/12/17* @since 1.0.0*/
@Component("biQuPuller")
@Slf4j
public class BiQuPuller implements NewsPuller {@Value("${book.biqu.url}")private String url;@Overridepublic void pullNews() {log.info("开始拉取...");//1.获取首页Document html=null;try {html=getHtmlFromUrl(url, false);}catch (Exception e){log.error("拉取失败...url--->{}",url);return;}//获取首页中热点内容Elements hotBooks = html.select("div#main").select("div#hotcontent").select("div.l").select("a[href~=^http://www.xbiquge.*]");HashSet<String> urls=new HashSet<>();hotBooks.forEach(item->{//小说的地址String href = item.attr("href");urls.add(href);});//爬取每一个小说,这里爬取了一篇小说,就break了,如果需要多篇热门小说打开break即可for (String s : urls) {pull(s);break;}}/*** 爬取每一篇小说的章节**/public void pull(String surl){log.info("开始拉取...");//1.获取首页Document html=null;try {html=getHtmlFromUrl(surl, false);}catch (Exception e){log.error("拉取失败...url--->{}",surl);return;}Elements elements = html.select("div#list").select("dl").select("dd > a");HashSet<String> zhangjieUrl=new HashSet<>();elements.forEach(element -> {String href = element.attr("href");String title = element.text();  //章节标题//章节链接href=url+href;System.out.println(title+"     -->    "+href);zhangjieUrl.add(href);});//爬取小说里每一个章节,这里爬取了一个章节,就break了,如果需要多篇热门小说打开break即可for (String s : zhangjieUrl) {pullContent(s);break;}}/*** 爬取每一章节内容* @param contentUrl*/public void pullContent(String contentUrl){log.info("开始拉取...");Document html=null;try {html=getHtmlFromUrl(contentUrl, false);}catch (Exception e){log.error("拉取失败...url--->{}",contentUrl);return;}Elements content = html.select("div#content");
//        System.out.println(content);content.forEach(c->{//获取纯文字内容,不带标签  (章节内容)System.out.println(c.text());});}
}
第四步:测试

在这里插入图片描述

@SpringBootApplication
public class CrawlerApplication {public static void main(String[] args){SpringApplication.run(CrawlerApplication.class,args);}
}

采用springboot test进行测试

@SpringBootTest
@RunWith(SpringRunner.class)
public class PullTest {@Autowired@Qualifier("biQuPuller")private CommonPuller biQuPuller;@Testpublic void testBiQu(){biQuPuller.pullNews();}
}
至此,爬虫的简单demo已经实现,核心还是在于对html页面标签的分析.

代码地址:https://github.com/itapechang/biqu-crawler.git 克隆下来直接在test包下运行即可

这篇关于[JAVA] Jsoup爬虫(新笔趣网)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种

Java docx4j高效处理Word文档的实战指南

《Javadocx4j高效处理Word文档的实战指南》对于需要在Java应用程序中生成、修改或处理Word文档的开发者来说,docx4j是一个强大而专业的选择,下面我们就来看看docx4j的具体使用... 目录引言一、环境准备与基础配置1.1 Maven依赖配置1.2 初始化测试类二、增强版文档操作示例2.

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.