【问题标题】:How can I read into a webpage non-linked text with jsoup?如何使用 jsoup 读入网页非链接文本?
【发布时间】:2023-03-29 09:53:01
【问题描述】:

我知道,如果我想用 Jsoup 打印链接和链接文本,我必须使用以下代码:

        Document doc = Jsoup.connect("https://en.wikipedia.org/wiki/Jsoup").get();
        Elements links = doc.select("a[href]");
        for (Element link : links) {
            System.out.println(link.attr("abs:href") + " - " + link.text());
        }

输出:(不完整)

   https://en.wikipedia.org/wiki/Jsoup#mw-head - Jump to navigation
   https://en.wikipedia.org/wiki/Jsoup#p-search - Jump to search
   https://en.wikipedia.org/wiki/Software_developer - Developer(s)
   https://en.wikipedia.org/wiki/Software_release_life_cycle - Stable release 
   https://en.wikipedia.org/wiki/Jsoup#cite_note-1 - [1]
   https://en.wikipedia.org/wiki/Jsoup#cite_note-2 - [2]
   https://en.wikipedia.org/wiki/Repository_(version_control) - Repository 
   https://github.com/jhy/jsoup - github.com/jhy/jsoup
   ...

如果我想打印整个网页的文本,我必须使用以下代码:

System.out.println(doc.body().text());

输出:(不完整)

jsoup 来自维基百科,免费的百科全书 跳转到导航 跳转到 search jsoup Java HTML Parser Developer(s) Jonathan Hedley Stable 发布 1.11.3 [1] / 2018-04-15 [2] 存储库 github.com/jhy/jsoup...

如何打印没有链接文本的文档的所有文本?

输出我想要的:

jsoup 来自维基百科,免费的百科全书 jsoup Java HTML 解析器 Jonathan Hedley 1.11.3 / 2018-04-15 ...

【问题讨论】:

    标签: java jsoup


    【解决方案1】:

    Jsoup 的Elements 有一个remove() 方法。这应该会从您的文档中删除链接。

    Document doc = Jsoup.connect("https://en.wikipedia.org/wiki/Jsoup").get();
    doc.select("a[href]").remove();
    System.out.println(doc.body().text());
    

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      相关资源
      最近更新 更多