Jsoup如何让jQuery像选择器一样? [英] How does Jsoup make jQuery like selectors?

查看:171
本文介绍了Jsoup如何让jQuery像选择器一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我过去使用过jsoup,我似乎无法理解如何定义jquery像选择器。我已经阅读了源代码,但我仍然无法理解。

I've used jsoup in the past and I can't seem to understand how the jquery like selectors are being defined. I've read the source code and I still can't understand.

public static final class ContainsOwnText extends Evaluator {
        private String searchText;

        public ContainsOwnText(String searchText) {
            this.searchText = searchText.toLowerCase();
        }

        @Override
        public boolean matches(Element root, Element element) {
            return (element.ownText().toLowerCase().contains(searchText));
        }

        @Override
        public String toString() {
            return String.format(":containsOwn(%s", searchText);
        }
    }

以上可以这样调用

select("*:containsOwn("+ str + ")");

这是选择

问题:

有人可以向我解释ContainsOwn有效吗?

Can someone explain to me how the ContainsOwn works?







return String.format(":containsOwn(%s", searchText);

为什么上面是不是这样?

Why the above is not like this?

return String.format(":containsOwn(%s)", searchText);

这里是评估员

我问,因为我想了解jsoup是如何工作的,这不是我在制作上遇到麻烦这行得通。我只是想知道它是如何完成的。如果我想用类似jquery的选择器复制这种行为,并想开发类似的东西我该怎么做?

I'm asking because I want to understand how jsoup works, it's not I'm having a trouble making it work. I just want to know how it's done. If I wanted to replicate this behavior with the jquery-like selectors and wanted to develop something similar what should I do?

推荐答案

你调用 select(query)解析该查询以填充一组评估器,然后将这些评估器传递给收集器以构造一组满足查询的元素。

When you call select(query) that query is parsed to populate a set of evaluators, which are then passed to the Collector to construct a set of elements that satisfy the query.

在这种情况下, QueryParser containsOwn 操作导致包含要调用的第325行上的方法,它创建 ContainsOwn 求值程序的实例。

In this case the QueryParser on line 162 the containsOwn operation causes the contains method on line 325 to be called, which creates an instance of ContainsOwn evaluator.

此评估者传递给 收集器 遍历树,调用匹配每个评估者的方法。在这种情况下(在 ContainsOwn 中)匹配方法使用包含 java.lang.String 的方法,检查给定的字符串是否包含在元素的自己的文本中。

This evaluator is passed to the Collector that traverses the tree calling the matches method of each evaluator. In this case (in ContainsOwn) the matches method uses the contains method of java.lang.String to check if the given string is contained within the own text of the element.

ContainsOwn 中的 toString 方法已编写为镜像用于创建它的语法,并且对它是如何创建的(这由QueryParser处理)。缺少一个封闭的括号看起来像一个无害的拼写错误。

The toString method in ContainsOwn has been written to mirror the syntax used to create it and has no effect on how it is created (this is dealt with by the QueryParser). The lack of a closed parenthesis looks like a harmless typo.

这篇关于Jsoup如何让jQuery像选择器一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆