Jsoup怎样从Html文件中提取正文内容?

html-css018

Jsoup怎样从Html文件中提取正文内容?,第1张

Jsoup从Html文件中提取正文内容\x0d\x0a示例代码:\x0d\x0aFileinput=newFile("/tmp/input.html")\x0d\x0aDocumentdoc=Jsoup.parse(input,"UTF-8","/example.com/")\x0d\x0a\x0d\x0aElementcontent=doc.getElementById("content")\x0d\x0aElementslinks=content.getElementsByTag("a")\x0d\x0afor(Elementlink:links){\x0d\x0aStringlinkHref=link.attr("href")\x0d\x0aStringlinkText=link.text()\x0d\x0a}\x0d\x0ajsoup是一款Java的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于JQuery的操作方法来取出和操作数据。\x0d\x0ajsoup的主要功能如下:\x0d\x0a1.从一个URL,文件或字符串中解析HTML;\x0d\x0a2.使用DOM或CSS选择器来查找、取出数据;\x0d\x0a3.可操作HTML元素、属性、文本;

Jsoup从Html文件中提取正文内容

示例代码:

File input = new File("/tmp/input.html")

Document doc = Jsoup.parse(input, "UTF-8", "/example.com/")

Element content = doc.getElementById("content")

Elements links = content.getElementsByTag("a")

for (Element link : links) {

String linkHref = link.attr("href")

String linkText = link.text()

}

jsoup是一款Java的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于JQuery的操作方法来取出和操作数据。

jsoup的主要功能如下:

1. 从一个URL,文件或字符串中解析HTML;

2.使用DOM或CSS选择器来查找、取出数据;

3. 可操作HTML元素、属性、文本;

/**

* 这个文件实现了:将指定目录下的所有htm和html文件的<title>标签的值,替换成文件名(不含后缀)。

*/

import java.io.File

import java.io.FileOutputStream

import java.io.IOException

import java.io.OutputStreamWriter

import org.jsoup.Jsoup

import org.jsoup.nodes.Document

import org.jsoup.nodes.Element

public class Rename {

public static void main(String[] args) {

// 默认文件夹路径

String path = "C:\\report"

if(args != null &&args.length >0){

path = args[0]

}

try {

renameHTMLTitle(path)

} catch (IOException e) {

e.printStackTrace()

}

}

public static void renameHTMLTitle(String dir) throws IOException {

File f = new File(dir)

if (f.isDirectory()) {

File fs[] = f.listFiles()

for (File s : fs) {

String title = s.getName().replaceAll(".htm", "").replaceAll(".html", "")

if(s.getName().contains(".htm") || s.getName().contains(".html")){

Document doc = Jsoup.parse(s, "gb2312")

Element titleEl = doc.select("title").first()

titleEl.html(title)

/*

* Jsoup只是解析,不能保存修改,所以要在这里保存修改。

*/

FileOutputStream fos = new FileOutputStream(s, false)

OutputStreamWriter osw = new OutputStreamWriter(fos, "gb2312")

osw.write(doc.html())

osw.close()

}

}

}

}

}