Java中使用Jsoup实现网页内容爬取与Html内容解析并使用EasyExcel实现导出为Excel文件

news2024/10/6 4:01:06

场景

Pythont通过request以及BeautifulSoup爬取几千条情话:

Pythont通过request以及BeautifulSoup爬取几千条情话_爬取情话-CSDN博客

Node-RED中使用html节点爬取HTML网页资料之爬取Node-RED的最新版本:

Node-RED中使用html节点爬取HTML网页资料之爬取Node-RED的最新版本_node-red html-CSDN博客

Jsoup

Jsoup是一种Java 的HTML(html也是XML文档)解析器,可直接解析某个URL地址、HTML文本内容。

它提供了一套易于操作的API,可通过DOM,CSS以及类似于jQuery选择器的操作方法来取出和操作数据。

使用jsoup就可以解析HTML。

Jsoup使用的是DOM解析方式,把整个HTML文档(XML文档)加载到内存中形成一棵DOM树,得到文档的Document对象。

HTML里的标签,会转换成Element对象。

官网地址:

jsoup: Java HTML parser, built for HTML editing, cleaning, scraping, and XSS safety

EasyExcel

Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,

poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,

比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。

easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,

改用easyexcel可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,

在上层做了模型转换的封装,让使用者更加简单方便。

官网地址:

关于Easyexcel | Easy Excel

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi 

实现

1、引入依赖

        <!--Jsoup 是一个用于解析HTML和XML文档的Java库-->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.3</version>
        </dependency>

        <!--EasyExcel是一个基于Java的、快速、简洁、解决大文件内存溢出的Excel处理工具-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.0.5</version>
        </dependency>

2、找到需要爬取的网页内容

比如以下面为例

2023财富世界500强企业榜单 2023全球500强企业 世界500强排名一览表→买购网

这里要获取500强排名数据,因为单次刷新网页只能返回100条数据,所以只解析前100条。获取更多数据可根据其分页请求规则分别进行爬取。

打开F12找到要爬取的数据的dom结构

这里要获取到id为t_container的div元素大的第22个子元素(索引为21)的table元素的tr元素的td数据。

3、编写测试代码,连接并解析html元素

        String url = "https://www.maigoo.com/news/3jcNODk3.html";
        try {
            //读取url,得到Document
            Document document = Jsoup.connect(url)
                    .ignoreContentType(true)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3")
                    .timeout(30000)
                    .header("referer","https://www.maigoo.com")
                    .get();
            Elements select = document.select("#t_container > div:eq(21) table tr");
        } catch (IOException e) {
            e.printStackTrace();
        }

注意这里使用选择器的语法:

#t_container 代表id为t_container

>代表找父元素下的子元素

div:eq(21) 代表第22个元素

table tr 代表table 标签下tr标签

更多select选择器用法

Use CSS selectors to find elements: jsoup Java HTML parser

Selector overview

  • tagname: find elements by tag, e.g. div
  • #id: find elements by ID, e.g. #logo
  • .class: find elements by class name, e.g. .masthead
  • [attribute]: elements with attribute, e.g. [href]
  • [^attrPrefix]: elements with an attribute name prefix, e.g. [^data-] finds elements with HTML5 dataset attributes
  • [attr=value]: elements with attribute value, e.g. [width=500] (also quotable, like [data-name='launch sequence'])
  • [attr^=value][attr$=value][attr*=value]: elements with attributes that start with, end with, or contain the value, e.g. [href*=/path/]
  • [attr~=regex]: elements with attribute values that match the regular expression; e.g. img[src~=(?i)\.(png|jpe?g)]
  • *: all elements, e.g. *
  • ns|tag: find elements by tag in a namespace prefix, e.g. fb|name finds <fb:name> elements
  • *|tag: final elements by tag in any namespace prefix, e.g. *|name finds <fb:name> and <name> elements

Selector combinations

  • el#id: elements with ID, e.g. div#logo
  • el.class: elements with class, e.g. div.masthead
  • el[attr]: elements with attribute, e.g. a[href]
  • Any combination, e.g. a[href].highlight
  • ancestor child: child elements that descend from ancestor, e.g. .body p finds p elements anywhere under a block with class "body"
  • parent > child: child elements that descend directly from parent, e.g. div.content > p finds p elements; and body > * finds the direct children of the body tag
  • siblingA + siblingB: finds sibling B element immediately preceded by sibling A, e.g. div.head + div
  • siblingA ~ siblingX: finds sibling X element preceded by sibling A, e.g. h1 ~ p
  • el, el, el: group multiple selectors, find unique elements that match any of the selectors; e.g. div.masthead, div.logo

Pseudo selectors

  • :has(selector): find elements that contain elements matching the selector; e.g. div:has(p)
  • :is(selector): find elements that match any of the selectors in the selector list; e.g. :is(h1, h2, h3, h4, h5, h6) finds any heading element
  • :not(selector): find elements that do not match the selector; e.g. div:not(.logo)
  • :contains(text): find elements that contain the given text. The search is case-insensitive; e.g. p:contains(jsoup)
  • :containsOwn(text): find elements that directly contain the given text
  • :matches(regex): find elements whose text matches the specified regular expression; e.g. div:matches((?i)login)
  • :matchesOwn(regex): find elements whose own text matches the specified regular expression
  • :lt(n): find elements whose sibling index (i.e. its position in the DOM tree relative to its parent) is less than n; e.g. td:lt(3)
  • :gt(n): find elements whose sibling index is greater than n; e.g. div p:gt(2)
  • :eq(n): find elements whose sibling index is equal to n; e.g. form input:eq(1)
  • Note that the above indexed pseudo-selectors are 0-based, that is, the first element is at index 0, the second at 1, etc

除使用select选择器之外还可使用XPath选择器用法

Use XPath selectors to find elements and nodes: jsoup Java HTML parser

4、解析dom数据并赋值到对象添加到list

新建实体对象,并添加excel注解

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Builder;
import lombok.Data;

import java.io.Serializable;

@Data
@Builder
public class WealthEntity implements Serializable {

    private static final long serialVersionUID = -1760099890427975758L;

    @ExcelProperty(value = "排名",index = 0)
    private Integer index;

    @ExcelProperty(value = "公司名称",index = 1)
    private String companyName;

    @ExcelProperty(value = "收入",index = 2)
    private String income;

    @ExcelProperty(value = "利润",index = 3)
    private String profit;

}

进行dom解析和添加到list

            Elements select = document.select("#t_container > div:eq(21) table tr");
            List<WealthEntity> list = new ArrayList<>();
            for (int i = 1; i < select.size(); i++) {
                Element tr = select.get(i);
                Elements tds = tr.select("td");
                Integer index = Integer.valueOf(tds.get(0).text());
                String companyName = tds.get(1).text();
                String income = tds.get(2).text();
                String profit = tds.get(3).text();
                WealthEntity wealthEntity = WealthEntity.builder()
                        .index(index)
                        .companyName(companyName)
                        .income(income)
                        .profit(profit)
                        .build();
                list.add(wealthEntity);
            }

5、导出为excel

            String fileName = "D:/2023财富世界100强.xlsx";
            EasyExcel.write(fileName,WealthEntity.class).sheet("100强").doWrite(list);

6、完整示例代码

        String url = "https://www.maigoo.com/news/3jcNODk3.html";
        try {
            //读取url,得到Document
            Document document = Jsoup.connect(url)
                    .ignoreContentType(true)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3")
                    .timeout(30000)
                    .header("referer","https://www.maigoo.com")
                    .get();
            Elements select = document.select("#t_container > div:eq(21) table tr");
            List<WealthEntity> list = new ArrayList<>();
            for (int i = 1; i < select.size(); i++) {
                Element tr = select.get(i);
                Elements tds = tr.select("td");
                Integer index = Integer.valueOf(tds.get(0).text());
                String companyName = tds.get(1).text();
                String income = tds.get(2).text();
                String profit = tds.get(3).text();
                WealthEntity wealthEntity = WealthEntity.builder()
                        .index(index)
                        .companyName(companyName)
                        .income(income)
                        .profit(profit)
                        .build();
                list.add(wealthEntity);
            }
            String fileName = "D:/2023财富世界100强.xlsx";
            EasyExcel.write(fileName,WealthEntity.class).sheet("100强").doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }

7、运行结果

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1494950.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

mybatis单表curd笔记(尚硅谷

Mybatis 11111ibatis和mybatis不同 查询文档mybatis的日志输出id赋值输入&#xff08;向sql语句传入数据单个简单类型单个实体对象多个简单类型map类型 输出数据的指定单个简单类型单个实体类型输出map类型输出list输出类型主键回显&#xff08;自增长类型主键回显&#xff08;…

强大的ps 命令 -o 自定义输出内容选项

强大的ps 命令 -o 自定义输出内容选项 1、ps命令介绍和作用2、问题描述 1、ps命令介绍和作用 ps 是一个 Unix 和类 Unix 操作系统中常用的命令&#xff0c;用于显示当前运行的进程信息。ps 命令的作用包括&#xff1a; 查看进程信息&#xff1a; ps 命令可以列出当前系统中正…

【自然语言处理】【大模型】BitNet:用1-bit Transformer训练LLM

BitNet&#xff1a;用1-bit Transformer训练LLM 《BitNet: Scaling 1-bit Transformers for Large Language Models》 论文地址&#xff1a;https://arxiv.org/pdf/2310.11453.pdf 相关博客 【自然语言处理】【大模型】BitNet&#xff1a;用1-bit Transformer训练LLM 【自然语言…

Matlab梁单元有限元编程 | 铁木辛柯梁 | 欧拉梁 | Matlab源码 | 理论文本

专栏导读 作者简介&#xff1a;工学博士&#xff0c;高级工程师&#xff0c;专注于工业软件算法研究本文已收录于专栏&#xff1a;《有限元编程从入门到精通》本专栏旨在提供 1.以案例的形式讲解各类有限元问题的程序实现&#xff0c;并提供所有案例完整源码&#xff1b;2.单元…

【网络安全】漏洞挖掘入门教程(非常详细),小白是如何挖漏洞(技巧篇)0基础入门到精通!

温馨提示&#xff1a; 初学者最好不要上手就去搞漏洞挖掘&#xff0c;因为漏洞挖掘需要很多的系统基础知识和一些理论知识做铺垫&#xff0c;而且难度较大…… 较合理的途径应该从漏洞利用入手&#xff0c;不妨分析一些公开的CVE漏洞。很多漏洞都有比较好的资料&#xff0c;分…

手写分布式配置中心(四)增加实时刷新功能(长轮询)

上一篇文章中实现了短轮询&#xff0c;不过短轮询的弊端也很明显&#xff0c;如果请求的频率较高&#xff0c;那么就会导致服务端压力大&#xff08;并发高&#xff09;&#xff1b;如果请求的频率放低&#xff0c;那么客户端感知变更的及时性就会降低。所以我们来看另一种轮询…

总结归纳Kubernetes | 一站式速查知识,助您轻松驾驭容器编排技术(水平扩展控制)

Kubernetes&#xff0c;亦被称为K8s&#xff0c;是业界公认的容器编排巨擘&#xff0c;以其卓越的能力简化了容器化应用的部署、扩展和管理流程。通过其强大的功能&#xff0c;Kubernetes不仅提升了应用的可靠性和可伸缩性&#xff0c;还优化了资源利用率&#xff0c;为开发者和…

MM配置1-定义、复制、删除、检查工厂

配置步骤&#xff0c;如下图&#xff1a; 双击“复制&#xff0c;删除&#xff0c;检查工厂选项” 点击“复制”按钮&#xff0c;输入参考工厂&#xff0c;和要新建的工厂 复制完成后&#xff0c;返回到上一界面&#xff0c;双击“定义工厂”选项 选中新建的1070工厂&#xff0…

java常用技术栈,java面试带答案

前言 我们从一个问题引入今天的主题。 在日常业务开发中&#xff0c;我们可能经常听到 DBA 对我们说“不要”&#xff08;注意&#xff1a;不是禁止&#xff09;使用 join&#xff0c;那么为什么 DBA 对 join 这么抵触呢&#xff1f;是 join 本身有问题&#xff0c;还是我们使…

HarmonyOS 数据持久化之首选项 preferences

接下来 我们来说说数据持久化的问题 我们平时处理的数据都是在内存中处理的 我们应用一点重启 所有数据都消失了 肯恩是不符合一些场景的 harmonyos中 提供了比较多的解决方案 最多的两种是 用户首选项 关系型数据库 本文的话 我们就来看看 用户首选项 首先&#xff0c;什么…

Android开发新手入门教程,android笔试面试题

前言 尤其是在最近一段时间内&#xff0c;感觉一天天的时间过得又慢又快&#xff0c;慢的是感觉复工了以后在公司的8.9个小时简直算是煎熬了&#xff0c;快的是常常感觉时间一天天&#xff0c;一月月的过去了&#xff0c;可是发现自己还在原路踏步走。看似每天忙成狗&#xff…

【数学建模】层次分析

1.建立递阶层次结构模型 2.构造出各层次中的所有判断矩阵 对指标的重要性进行两两比较&#xff0c;构造判断矩阵&#xff0c;科学求出权重 矩阵中元素aij的意义是&#xff0c;第i个指标相对第j个指标的重要程度 对角线1&#xff0c;aijaji1 矛盾——>一致性检验

win11配置Mask DINO小白踩坑记录

win11配置Mask DINO踩坑记录 1 准备工作2 创建python环境和安装detectron22.1 安装前提2.2 安装流程2.2.1 cl.exe的错误2.2.2 SetuptoolsDeprecationWarning的错误 3 MaskDINO运行3.1 运行demo 前情提要&#xff1a;需要复现Mask DINO&#xff0c;但是实验室没有Linux的电脑&am…

+++

解法&#xff1a; 显然a可以为aik&#xff08;i为整数&#xff09;&#xff0c;b可以为bjk(j为整数&#xff09;。 若aikbjk。假定i>j&#xff0c;那么a<b。可以得到b-a(i-j)k 我是傻逼&#xff0c;不放代码了 #include<iostream> #include<vector> #inc…

Tomcat基础与Nginx的动静分离

一、TOMCAT基础功能 &#xff08;一&#xff09;自动解压war包 在配置文件中讲到&#xff0c;当接受到请求后&#xff0c;会匹配符合要求的Host&#xff0c;在配置文件中的Host只有一个&#xff0c;且规定了自动解压war包 自动解压war包 .war&#xff1a;WebApp打包,类zip格…

【ESP32 IDF】SPI层次结构SPI协议与SPI控制器结构

文章目录 前言一、SPI 程序层次1.1 硬件原理图1.2 硬件框图1.3 软件层次 二、SPI协议2.1 硬件连线2.2 如何访问SPI设备2.3 SPI 框图 总结 前言 SPI&#xff08;Serial Peripheral Interface&#xff09;是一种常见的串行通信协议&#xff0c;用于在微控制器和外部设备之间进行…

Qt QtCreator打开pro项目时出现假死现象

在Windows系统下&#xff0c;QtCreator打开pro项目时出现假死现象&#xff0c;左侧项目树形图无法展开&#xff0c;项目根节点一直在转圈。尝试关掉所有QtCreator进程&#xff0c;重新打开pro也是无济于事。 解决方案&#xff1a; 打开“运行”窗口&#xff08;快捷键&#x…

鸿蒙文章专题-2021年鸿蒙相关的文章废弃

#原因 至于为什么说2021年我的鸿蒙专栏的文章废弃了&#xff0c;只是说没有了参考意义&#xff0c;是因为鸿蒙4.0以前的版本语言从以Java为主过渡为以ArkTS为主。以前的Java版本的工程已经无法再使用了&#xff0c;后续的开发都必须以ArkTS开发语言为主。 其中而且整个项目结构…

操作教程|使用MeterSphere对恒生UFX系统进行压力测试

恒生UFX&#xff08;United Finance Exchange&#xff0c;统一金融交换&#xff09;系统&#xff08;以下简称为“UFX系统”&#xff09;&#xff0c;是一款帮助证券公司统一管理外部接入客户的系统&#xff0c;该系统整体上覆盖了期货、证券、基金、银行、信托、海外业务等各类…

Python 服务实现可观测性最佳实践

前言 本次实践主要是介绍 Python 服务通过无侵入的方式接入观测云进行全面的可观测。 环境信息 系统环境&#xff1a;主机环境开发语言&#xff1a;Python2.7APM 探针包&#xff1a;ddtrace 接入方案 准备工作 安装 DataKit 主机安装 DataKit # 需要把token 改成观测云…