Java使用Xpath实现爬虫功能

看到有人通过Xpath实现爬虫功能,就写了一个Java版本的。
网上的其他教程看着都是用 过时的 方法实现的,我这是用的新方法,不会报错。

爬取了电影天堂 2022必看热片 里面的《电影名称》和对应下载链接。

在这里插入图片描述
下面贴代码:
需要先引入Xpath的jar包

// https://mvnrepository.com/artifact/cn.wanghaomiao/JsoupXpath
    implementation 'cn.wanghaomiao:JsoupXpath:2.2'
package xpath;

import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;

import java.util.List;

/**
 * Xpath测试
 *
 * @author zhao.hualuo
 * Create at 2022/6/9
 */
public class XpathTest {

    public static void main(String[] args) {
        String html= "https://www.dytt89.com/";
        // 基于URL创建JXDocument
        JXDocument jxDocument = JXDocument.createByUrl(html);
        // Xpath语句
        String str = "//*[@id=\"header\"]/div/div[3]/div[4]/div[2]/div[2]/ul";
        // 获取节点集合
        List<JXNode> list = jxDocument.selN(str);
        Element element = list.get(0).asElement();
        // 遍历节点
        for (Node childNode : element.childNodes()) {
            if (childNode.childNodes().size() == 0) {
                continue;
            }
            Attributes attributes = childNode.childNodes().get(0).attributes();
            String href = childNode.baseUri() + attributes.get("href").substring(1);
            String title = attributes.get("title");
            System.out.println(href + "\t" + title);
        }
    }
}

下面讲解一下2个核心参数

//这个是要爬取的网站
String html= "https://www.dytt89.com/";

//这个是xpath规则,可以直接在网页获取,下面是获取方法
String str = "//*[@id=\"header\"]/div/div[3]/div[4]/div[2]/div[2]/ul";

在这里插入图片描述

代码其实没啥东西,可以拆成两部分

  1. 我上面讲的2个参数
  2. 拼接自己需要的数据

在这里插入图片描述
代码执行结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值