首页 \ 问答 \ 提取内部元素而不循环(Extract inner element without looping)

提取内部元素而不循环(Extract inner element without looping)

如果我循环遍历所有,则从以下示例HTML代码中提取href值是直截了当的 并在第一个之后立即中断:

  <li class="parts partname parts_first">
    <div id="dpdn10" uri="/public/page/part1" class="partype partstate">
      <div class="ptctainer">
        <div class="ptitle">
          <p class="ptypead">
            <span class="rtext"><a href="http://www.example.com/page/ptname.html?dv=rfirst" class="mnLabel">First</a></span>
            <span class="ndx">
              <a href="#" dndx="dpdn10" class="xpnd _t" style="opacity:1">Details: </a>
            </span>
          </p>
        </div>
      </div>

      <div id="dpdn10_content" class="xpns">
        <div class="ptctainer">
          <div class="ptitle">
            <p class="ptypead">
              <span class="rtext"><a href="http://www.example.com/page/ptname.html?dv=rfirst" class="mnLabel">First</a></span>
              <span class="ndx"><a href="#" class="xpnd">Details: </a></span>
            </p>
          </div>
        </div>    
      </div>
    </div>
  </li>

当我可以假设两个实例的href值相同时,我当然可以这样做 如上例所示。

但是,如果它们不相同并且我想提取特定的(第一个或第二个),则此方法会失败。

这让我在Jsoup中搜索允许“嵌套选择”的机制:到目前为止,我已熟悉单级选择,如:

Elements links = doc.select("a[href]"); // a with href
Elements pngs = doc.select("img[src$=.png]");  // img with src ending .png
Element masthead = doc.select("div.masthead").first();  // div with class=masthead

但我找不到文档或多级选择的例子,例如

Element link= doc.select("div.xpns.div.ptctainer.div.ptitle.p.ptypead.span.rtext");

当然,上面的内容仅用于说明而不是真正的语法。 我不知道Jsoup中是否还有这样的东西。

Jsoup中是否存在这种“嵌套选择”?


Extracting the href value from the following sample HTML code is straight forward if I loop through all and break immediately after the first one:

  <li class="parts partname parts_first">
    <div id="dpdn10" uri="/public/page/part1" class="partype partstate">
      <div class="ptctainer">
        <div class="ptitle">
          <p class="ptypead">
            <span class="rtext"><a href="http://www.example.com/page/ptname.html?dv=rfirst" class="mnLabel">First</a></span>
            <span class="ndx">
              <a href="#" dndx="dpdn10" class="xpnd _t" style="opacity:1">Details: </a>
            </span>
          </p>
        </div>
      </div>

      <div id="dpdn10_content" class="xpns">
        <div class="ptctainer">
          <div class="ptitle">
            <p class="ptypead">
              <span class="rtext"><a href="http://www.example.com/page/ptname.html?dv=rfirst" class="mnLabel">First</a></span>
              <span class="ndx"><a href="#" class="xpnd">Details: </a></span>
            </p>
          </div>
        </div>    
      </div>
    </div>
  </li>

I can certainly do that when I can assume the href value is identical for both instances of as in the example above.

However, this approach fails if they are not identical and I want to extract a specific one (either the first or the second).

Which brings me to searching for a mechanism in Jsoup that allows "nested selection": Up until now I have been familiar with single-level selection as in:

Elements links = doc.select("a[href]"); // a with href
Elements pngs = doc.select("img[src$=.png]");  // img with src ending .png
Element masthead = doc.select("div.masthead").first();  // div with class=masthead

But I can't find documentation or an example for multi-level selection, e.g.

Element link= doc.select("div.xpns.div.ptctainer.div.ptitle.p.ptypead.span.rtext");

The above is for illustration and not real syntax, of course. I don't know if something like this is possible (yet) in Jsoup.

Does such "nested selection" exist in Jsoup?


原文:https://stackoverflow.com/questions/5771462
更新时间:2022-05-21 11:05

最满意答案

发生这种情况是因为您传递的是“4 2 1 -5”而不是作为参数,因此它们会进入main方法的args参数。 要将它们作为输入传递,请等待应用程序启动并输入它们或使用输入流重定向

更新 (参数处理代码)

我应该如何在java中编写它以将输入作为参数呢? 有一个特定的简单方法吗?

我会说使用非固定数量的输入参数的参数并不是一个好主意。 我仍然说使用输入流是要走的路 - 这就是它的设计目的! 您的解析要求也有点不合理。 我的尝试还在这里

public class Main
{
    static OptionalInt parseOnlyInt(String s)
    {
        String digitsOnly = s.replaceAll("[^0-9]", "");
        if (digitsOnly.length() == 0)
            return OptionalInt.empty();
        else
            return OptionalInt.of(Integer.parseInt(digitsOnly));
    }

    public static void main(String[] args)
    {
        int sum = Arrays.stream(args)
                .map(Main::parseOnlyInt)
                // probably in Java 9 OptionalInt::stream would be better than next 2 lines
                // see https://bugs.openjdk.java.net/browse/JDK-8050820
                .filter(OptionalInt::isPresent)
                .mapToInt(OptionalInt::getAsInt)
                .sum(); 

        System.out.println(Arrays.toString(args));
        System.out.println(sum);    
    }
}

或者,如果您更喜欢旧的(非Java-8)方式,那么它就是

public static void main(String[] args)
{
    int sum = 0;
    for (int i = 0; i < args.length; i++)
    {
        String digitsOnly = args[i].replaceAll("[^0-9]", "");
        if (digitsOnly.length() != 0)
            sum += Integer.parseInt(digitsOnly);
    }
    System.out.println(Arrays.toString(args));
    System.out.println(sum);
}

This happens because you pass "4 2 1 -5" not as input but as arguments so they come into args parameter of the main method. To pass them as input wait till the app starts and enter them or use input stream redirection

Update (code for arguments processing)

How should I write it in java to take input as arguments then? Is there a specific easy way?

I'd say that using arguments for non-fixed number of input params is not so good idea. I'd still say that using input stream is the way to go - this is what it was designed for! Also your parsing requirements are a bit umbigious. Still here is my attempt

public class Main
{
    static OptionalInt parseOnlyInt(String s)
    {
        String digitsOnly = s.replaceAll("[^0-9]", "");
        if (digitsOnly.length() == 0)
            return OptionalInt.empty();
        else
            return OptionalInt.of(Integer.parseInt(digitsOnly));
    }

    public static void main(String[] args)
    {
        int sum = Arrays.stream(args)
                .map(Main::parseOnlyInt)
                // probably in Java 9 OptionalInt::stream would be better than next 2 lines
                // see https://bugs.openjdk.java.net/browse/JDK-8050820
                .filter(OptionalInt::isPresent)
                .mapToInt(OptionalInt::getAsInt)
                .sum(); 

        System.out.println(Arrays.toString(args));
        System.out.println(sum);    
    }
}

Or if you prefer the old (non-Java-8) way here it is

public static void main(String[] args)
{
    int sum = 0;
    for (int i = 0; i < args.length; i++)
    {
        String digitsOnly = args[i].replaceAll("[^0-9]", "");
        if (digitsOnly.length() != 0)
            sum += Integer.parseInt(digitsOnly);
    }
    System.out.println(Arrays.toString(args));
    System.out.println(sum);
}

相关问答

更多
  • 如果您使用WaitForExit,您的应用程序将阻塞(等待),直到该进程退出。 这意味着它无法在其UI线程中处理任何Windows消息,因此它不会更新UI。 您需要“在后台”启动该过程,以便您的UI继续刷新。 这可以通过以下方式完成: 从单独的线程启动并监视进程,并将进度信息传递回UI线程以供显示 向进程退出事件添加事件处理程序,或定期轮询process.HasExited标志,并使用它来了解第一个进程何时完成。 您的事件处理程序将关闭此进程,然后退回到主应用程序循环,以便在等待外部进程完成时正常运行。 坐 ...
  • 发生这种情况是因为您传递的是“4 2 1 -5”而不是作为参数,因此它们会进入main方法的args参数。 要将它们作为输入传递,请等待应用程序启动并输入它们或使用输入流重定向 更新 (参数处理代码) 我应该如何在java中编写它以将输入作为参数呢? 有一个特定的简单方法吗? 我会说使用非固定数量的输入参数的参数并不是一个好主意。 我仍然说使用输入流是要走的路 - 这就是它的设计目的! 您的解析要求也有点不合理。 我的尝试还在这里 public class Main { static Optiona ...
  • 你必须为app启动设置参数。 您可以在运行配置编辑器中执行此操作(右键单击项目 - >运行方式 - >运行配置)。 在Arguments选项卡中,您可以将其中一个设置为Arguments字段。 每行一个参数(例如5)。 发生ArrayIndexOutOfBoundsException是因为您要采用空数组的第一个元素 - args[0]的空args数组。 你不能这样做,因为如果没有设置应用程序启动参数,数组是空的。 you have to set arguments for app start up. You ...
  • 我怀疑这与你如何得到你的输入有关。 试试这个,让我知道它是否有效: System.out.println("\nTitle of the student (eg, Mr, Ms): "); String title = keyboard.next(); while (!title.equals("Mr") && !title.equals("Ms") && !title.equals("mr") && !title.equals("ms")) { { System.out.println("Atten ...
  • 我不认为你的扫描仪/阅读器是这里的问题。 在您的getBook方法中,尝试将标题与equals进行比较 if (books[i].title.equals(title)) { 我假设你的.title方法返回一个带有书名的字符串,如果你称之为getTitle它会更容易理解 你可以尝试使用缓冲阅读器 InputStream is = System.in; BufferedReader in = new BufferedReader(new InputStreamReader(is)); ...
  • @ User3805967说,这可能是一个UI问题。 所以我设置一个断点来检查,如果while循环工作。 循环就像它应该的那样工作。 所以我尝试在生成所有数字后将ArrayAdapter传递给ListView。 而且效果很好。 现在我的代码看起来像下面的例子: FindViewById
  • 试过以下。 int[][] interval = new int [15][5]; int intRow = 1; int _START_ = 0; int _END_ = 1; interval[intRow][_START_] = 1; interval[intRow][_END_] = 2; for ( int row = interval[intRow][_START_]; row <= interval[intRow][_END_]; row++ ) { System.out.pr ...
  • 你犯了所有常见的错误,还有一些错误。 整个请求无法保证一次性读取。 您不能假设已经到达多个字节。 你必须循环。 您没有在此阶段检查流的结束。 您需要熟悉RFC 2616才能实现HTTP,特别是有关内容长度和传输编码的部分。 您不能假设服务器在发送响应后将关闭连接。 关闭输入或输出流或套接字会关闭套接字。 这就是你的SocketException: socket closed的原因。 当你到达HTTPS时,你需要查看CONNECT动词。 刷新套接字输出流什么都不做,并且应避免在循环内刷新, You are m ...
  • 而不是这个 click
    像这样使用 click
    来自@Jonathan Lonowski的精彩解释 为 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)