如何从HTML获取链接,正确使用`doc.select`

时间:2018-12-10 23:26:49

标签: java html jsoup

我想从HTML代码中获取链接。此页面上的代码:https://www.valorebooks.com/books/fiction/fantasy

 <div class="sub_bar sub_bar_no_pointer"> 
         <span class="showing">Showing 1 - 50 of 28705 - Browse More Fantasy Books for Sale</span> 
         <div class="paginator" id="pg"> 
          <a href="/books/fiction/fantasy" class="active">1</a> 
          <a href="/books/fiction/fantasy?page=2">2</a> 
          <a href="/books/fiction/fantasy?page=3">3</a> 
          <a href="/books/fiction/fantasy?page=4">4</a> 
          <a href="/books/fiction/fantasy?page=5">5</a> 
          <span class="paginatorText">...</span> 
          <a href="/books/fiction/fantasy?page=575">575</a> 
          <span class="paginatorText">|</span> 
          <a href="/books/fiction/fantasy?page=2" class="spriteButton arrow     next icon-right-open"></a>
         </div> 
        </div> 

我找到了一个获取链接的示例,但是我不确定应该在doc.select("div.paginator");中写什么。是否正确,也许我应该用另一种方式写这个。

    Elements myLink = doc.select("div.paginator");      

    int number = 0;
    for (Element links : myLink) {
        Elements a = myLink.select("a[href]");                      // get links
        number = Integer.parseInt(a.get(a.size() - 2).text());
    }
    for (int i = 0; i < 20; i++) {
        getData(url + i);
    }
}

1 个答案:

答案 0 :(得分:2)

目前尚不清楚您要达到的目标。

要打印所有链接的字符串,可以执行以下操作:

Elements theLinks = doc.select("div.paginator").select("a[href]");

对于链接的Elements数组:

disp()