【问题标题】:How to keep this code repeating more than once如何使此代码重复多次
【发布时间】:2020-07-02 19:56:56
【问题描述】:

我的代码提取链接并将它们添加到 HashSet。我希望该链接替换原始链接并重复该过程,直到找不到要添加的新链接为止。程序继续运行,但链接没有更新,程序陷入无限循环,无所事事。如何更新链接,以便程序可以重复,直到找不到更多链接?

package downloader;

import java.io.IOException;
import java.net.URL;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Stage2 {
    public static void main(String[] args) throws IOException {

        int q = 0;
        int w = 0;


        HashSet<String> chapters = new HashSet();
        String seen = new String("/manga/manabi-ikiru-wa-fuufu-no-tsutome/i1778063/v1/c1");
        String source = new String("https://mangapark.net" + seen);
        //                          0123456789
       while( q == w ) {



        String source2 = new String(source.substring(21));

        String last = new String(source.substring(source.length() - 12));
        String last2 = new String(source.substring(source.length() - 1));


        chapters.add(seen);
        for (String link : findLinks(source)) {

            if(link.contains("/manga") && !link.contains(last) && link.contains("/i") && link.contains("/c") && !chapters.contains(link)) {
            chapters.add(link);
                System.out.println(link);
                seen = link;


                System.out.print(chapters);
                System.out.println(seen);
            }

            }

        }

      System.out.print(chapters);



    }

    private static Set<String> findLinks(String url) throws IOException {

        Set<String> links = new HashSet<>();

        Document doc = Jsoup.connect(url)
                .data("query", "Java")
                .userAgent("Mozilla")
                .cookie("auth", "token")
                .timeout(3000)
                .get();

        Elements elements = doc.select("a[href]");
        for (Element element : elements) {
            links.add(element.attr("href"));
        }


        return links;

    }

}

【问题讨论】:

  • 关于无限循环,while( q == w ) 确实会永远运行,因为这句话永远是正确的。你永远不会改变 q 或 w 的值。如果您希望它结束​​,您应该更改它,以便该值在某个时候返回 false。或者你可以使用break 声明。

标签: java replace while-loop jsoup hashset


【解决方案1】:

你的计划并没有因为你而停止,而条件永远不会改变:

while( q == w )

总是正确的。我没有一会儿就运行你的代码,我得到了 2 个链接打印两次(!)并且程序停止了。

如果您想要其他章节的链接,您会遇到和我一样的问题。在元素中

Element element = doc.getElementById("sel_book_1");

链接在伪元素 ::before 之后。因此它们不会出现在您的 Jsoup 文档中。

这是我对这个主题的问题:

How can I find a HTML tag with the pseudoElement ::before in jsoup

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多