jsoup+httpclient 抓取网页并解析网页

加入依赖:

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.19</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.15.4</version>
        </dependency>

代码:

package com.longqi.boothtml;

import cn.hutool.http.HttpUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * @author LongQi
 * @projectName boot-integration
 * @description: 抓取百度网页并获取链接页面数据
 * @date 2023/3/30 15:23
 */
public class HtmlPage {

    public static void main(String[] args) {
        try{
            String resp = HttpUtil.get("https://www.baidu.com",10000);
            System.out.println(resp);
            Document doc = Jsoup.parse(resp);
            Elements elements = doc.select("a");
            System.out.println("已查询到网页");
            int count = 0;
            for(Element element:elements){
                Attributes attrs = element.attributes();
                String url = attrs.get("href");
                if(url.startsWith("http")){
                    resp = HttpUtil.get(url);
                    System.out.println(resp);
                    count++;
                }
            }
            System.out.println("抓取了"+count+"个网页");
        }catch (Exception e){
            System.out.println("抓取异常");
            e.printStackTrace();
        }
    }
}

上面用Hutool的HttpUtil进行查询页面,接着哟昂Jsoup将页面转化为Document,再用选择器筛选出a标签,再轮询获取href属性的链接,最后一一访问。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙行天下_LXTX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值