簡體   English   中英

使用JSoup從所有頁面獲取結果

[英]Get results from all the pages using JSoup

我正在使用jsoup庫,今天遇到了一個問題。 我必須抓取DuckDuckGo並獲取每個頁面的查詢結果的所有標題,但是使用

Document doc = Jsoup.connect("https://duckduckgo.com/html/?q=" + query).get();

我只得到有關第一頁的結果。 我如何繼續下一頁?

您需要從每頁中提取表單參數,以獲取下一頁的請求參數。 這是這樣的:

   public static Map<String, String> getFormParams(final Document doc) {
        return doc.select("div.nav-link > form")
                .first()
                .select("input")
                .stream()
                .filter((input) -> {
                    return input.attr("name") != null && !input.attr("name").equals("");
                })
                .collect(Collectors.toMap(input -> input.attr("name"), input -> input.attr("value")));
    }

    public static void main(final String... args) throws IOException {
        final String baseURL = "https://duckduckgo.com/html";
        final Connection conn = Jsoup.connect(baseURL)
                .userAgent("Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19");
        conn.data("q", "search phrase"); // Change "search phrase"

        // 1st page
        final Document page1 = conn.get();

        final Map<String, String> formParams
                = getFormParams(page1);

        // 2nd page
        final Document page2 = conn.data(formParams).get();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM