【问题标题】:How to get the first link using JSOUP?如何使用 JSOUP 获取第一个链接?
【发布时间】:2020-10-27 22:41:25
【问题描述】:

我想使用 Jsoup 提取 google 搜索结果中的第一个链接。例如,我在 google 上搜索“apple”。我看到的第一个链接是www.apple.com/。如何返回第一个链接?我目前能够使用 Jsoup 提取所有链接:

       new Thread(new Runnable() {
        @Override
        public void run() {
            final StringBuilder stringBuilder = new StringBuilder();
            try {
                Document doc = Jsoup.connect(sharedURL).get();
                String title = doc.title();
                Elements links = doc.select("a[href]");
                stringBuilder.append(title).append("\n");
                for (Element link : links) {
                    stringBuilder.append("\n").append(" ").append(link.text()).append(" ").append(link.attr("href")).append("\n");
                }
            } catch (IOException e) {
                stringBuilder.append("Error : ").append(e.getMessage()).append("\n");
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // set text
                    textView.setText(stringBuilder.toString());
                }
            });
        }
    }).start();

【问题讨论】:

    标签: java android string jsoup


    【解决方案1】:

    你的意思是:

    Element firstLink = doc.select("a[href]").first();
    

    它对我有用。如果您的意思是别的,请告诉我们。我用以下内容检查了搜索结果,这是一个很难破译的结果,因为返回的结果类型非常多......地图、新闻、广告等。

    我使用 java lambdas 稍微整理了代码:

    public static void main(String[] args) {
            new Thread(() -> {
                final StringBuilder stringBuilder = new StringBuilder();
                try {
                    String sharedUrl = "https://www.google.com/search?q=apple";
                    Document doc = Jsoup.connect(sharedUrl).get();
                    String title = doc.title();
                    Elements links = doc.select("a[href]");
                    Element firstLink = links.first();  // <<<<< NEW ADDITION
                    stringBuilder.append(title).append("\n");
                    for (Element link : links) {
                        stringBuilder.append("\n")
                                .append(" ")
                                .append(link.text())
                                .append(" ")
                                .append(link.attr("href"))
                                .append("\n");
                    }
                } catch (IOException e) {
                    stringBuilder.append("Error : ").append(e.getMessage()).append("\n");
                }
                // replaced some of this for running/testing locally
                SwingUtilities.invokeLater(() -> System.out.println(stringBuilder.toString()));
            }).start();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2020-10-27
      • 2013-05-27
      • 1970-01-01
      相关资源
      最近更新 更多