【问题标题】:How to REPLACE html tags with characters using jsoup in java如何在java中使用jsoup用字符替换html标签
【发布时间】:2013-10-04 08:11:56
【问题描述】:

我正在使用 Java 代码从 Web 中提取信息进行处理,并且我正在使用 jsoup 库来清理从网站获得的响应中的 html 标记。现在,为了从这些代码中提取信息,我必须将 html 标记替换为很少使用的字符,例如“~”。

这是我的问题:

如何转换:

<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>

进入这个:

   ~This is heading 1~
   ~This is heading 2~
   ~This is heading 3~
   ~This is heading 4~
   ~This is heading 5~
   ~This is heading 6~

使用jsoup?

【问题讨论】:

  • 修改 org.jsoup.safety.Cleaner ??
  • What have you tried? 我的意思是除了问我们。
  • 我尝试了一种ceratin方法,但它只替换了标签内的内容......而不是整个标签

标签: java html tags jsoup


【解决方案1】:
String cssSelector = //add your selector. from the example you include i cant get a proper selector.
Document doc = Jsoup.parse("html")
Elements elms = doc.select(cssSelector)
for(Element elm:elms){
     System.out.println("~" + elm.text() + "~")
}

更新

如果你想替换 ALL 元素,你可以这样做:

html = html.replaceAll("<[^>]*>","~")

【讨论】:

  • 可能,您要选择什么?你能发布一个html样本吗?
  • 抱歉给您添麻烦了..这是我第一次使用Jsoup
  • 那你要选什么元素,里面没有h1,h2
  • 我想用'~'替换所有的HTML标签
  • 我以为你想替换特定元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-23
  • 1970-01-01
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 2013-03-17
相关资源
最近更新 更多