抱歉如果这个问题太简单了,但我找不到Java版本TagSoup的教程或文档。基本上,我想从互联网下载一个HTML网页并将其转换为包含在字符串中的XHTML。如何使用TagSoup实现此功能?
谢谢!
谢谢!
wget -O - example.com/bad.html | java -jar tagsoup.jar
或者,从Java开始:
解析HTML:
- 创建一个
org.ccil.cowan.tagsoup.Parser
的实例- 提供自己的 SAX2 ContentHandler
- 提供引用HTML的
InputSource
- 然后调用
parse()
!
以下是代码,它应该为您提供一种方法来拉取一个网页并使用TagSoup进行解析...
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://streak.espn.go.com/en/?date=20120824");
HttpResponse response = client.execute(request);
// Check if server response is valid
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
throw new IOException("Invalid response from server: " + status.toString());
}
// Pull content stream from response
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
try
{
XMLReader parser = XMLReaderFactory.createXMLReader("org.ccil.cowan.tagsoup.Parser");
// Use the TagSoup parser to build an XOM document from HTML
Document doc = new Builder(parser).build(builder.toString());
// Push your data to string or XML
doc.toString();
doc.toXML();
}
catch(IOException e)
{ ... }