除了我之前的问题:Extending a basic web crawler to filter status codes and HTML,我正在尝试使用以下方法从HTML标记中提取信息,在本例中为“标题”:
public static void parsePage() throws IOException, BadLocationException
{
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
Reader HTMLReader = new InputStreamReader(testURL.openConnection()
.getInputStream());
kit.read(HTMLReader, doc, 0);
// Create an iterator for all HTML tags.
ElementIterator it = new ElementIterator(doc);
Element elem;
while ((elem = it.next()) != null)
{
if (elem.getName().equals("title"))
{
System.out.println("found title tag");
}
}
}
这就是告诉我它找到了标签。 我正在努力的是如何提取其中/之后包含的信息。
我在网站上发现了这个问题:Help with Java Swing HTML parsing但是它声明它只适用于结构良好的HTML。 我希望还有另一种方式。
任何指示赞赏。
答案 0 :(得分:3)
尝试使用Jodd
Jerry jerry = jerry().enableHtmlMode().parse(html);
...
Parser parser = new Parser(htmlInput);
CssSelectorNodeFilter cssFilter = new CssSelectorNodeFilter("title");
NodeList nodes = parser.parse(cssFilter);
答案 1 :(得分:1)
结果将方法更改为此会产生所需的结果:
{
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
Reader HTMLReader = new InputStreamReader(testURL.openConnection().getInputStream());
kit.read(HTMLReader, doc, 0);
String title = (String) doc.getProperty(Document.TitleProperty);
System.out.println(title);
}
我认为我对使用迭代器/元素的东西进行了疯狂的追逐。