如何使用Jsoup和/或正则表达式Java从URL中删除html标记

时间:2015-07-17 18:04:50

标签: java html regex jsoup

我需要使用Java中的Jsoup和/或Regular Expressions从URL中删除HTML标记。 到目前为止,我已经尝试了几个东西,使用javax.swing.text.html.HTMLEditorKit甚至Jsoup,但是我无法交换导入java.io.FileReader;导入java.io.InputStreamReader; import java.net.URL;并使其成功运作。

我还能做什么?

这是我试过的代码**

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
import java.io.IOException;
import java.io.FileReader;
import java.io.Reader;
import org.jsoup.Jsoup;

public class WebTest {
  private WebTest() {}

  public static String extractText(Reader reader) throws IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(reader);
    String line;
    while ((line = br.readLine()) != null) {
      sb.append(line);
    }
    String textOnly = Jsoup.parse(sb.toString()).text();
    return textOnly;
  }




public static void main(String[] args) throws Exception {



  String filename = "/Users//Desktop/file4.csv";
  String urltodownload = "http://www.amazon.com";



  URL url = new URL(urltodownload);

  BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));

  BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filename)));

  String document = "";

  while (br.ready()) {

    String line = br.readLine();
    document += line + "\n";
    System.out.println( line );
  }  bw.close();

        String file = "/Users/Desktop/file4.csv";
        FileReader reader = new FileReader(file);
        System.out.println(WebTest.extractText(reader));
      }


}

2 个答案:

答案 0 :(得分:1)

使用Jsoup

public static String htmlremoved(String html) {
    return Jsoup.parse(html).text();
}

使用正则表达式String nohtml = YourUrlString.toString().replaceAll("\\<.*?>","");

答案 1 :(得分:0)

好的,谢谢所有贡献的人。我所做的似乎解决了我的问题是这个。将Jsoup.parse(String).text();添加到String line = br.readLine()的打印命令,如System.out.println( Jsoup.parse(line).text());,此代码将取出HTML标记。当然首先你必须声明方法public static String htmlremoved(String html) { return Jsoup.parse(html).text(); } 。您还可以将Jsoup.parse(String).text();代码添加到bw.write