如何使用jsoup获取网页上的所有链接?

时间:2020-10-09 23:15:26

标签: android jsoup

我正在尝试使用jsoup获取网页上的所有链接,并在textview中显示返回的链接。但是当我运行代码时,输​​出看起来像这样

<a class="Fx4vihref="ttps://google.com/search/howsearchworks/?fg=1"> How search works </a>

这只是一个链接,不是页面上的所有链接。这是我期望的输出-

  https://play.google.com/?hl=en&tab=w8
  https://www.google.com/calendar?tab=wc       
  https://photos.google.com/?tab=wq&pageId=none
  https://drive.google.com/?tab=wo

我在做什么错了?

代码:

   @SuppressLint("NewApi")
protected Elements doInBackground(String... urls) {

    String url = urls[0];
    Document doc;
    Elements links = null;

    try {
        //view.setText("this will be displayed in textview ");

        doc = Jsoup.connect(url).get();
        //view.setText("this wont be displayed in textview..i get unfortunately app stopped");
        links = doc.select("a[href]");


    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return links;
}

protected void onPostExecute(Elements result) {
    print("\nLinks: (%d)", result.size());

    for (Element link : result) {
        //view.setText((CharSequence) link);
        view.setText(link.toString());
        print(" * a: <%s>  (%s)", link.attr("abs:href"), trim(link.text(), 35));
    }
}

private static void print(String msg, Object... args) {
    System.out.println(String.format(msg, args));
}

private static String trim(String s, int width) {
    if (s.length() > width)
        return s.substring(0, width - 1) + ".";
    else
        return s;
}

}

0 个答案:

没有答案