Java - 打印 HTML 元素的任何细节

标签 java swing html-parsing

我是 Java 的新手,至少在与网络交互方面是这样。不管怎样,我正在制作一个必须从网页中获取 HTML 并解析它的应用程序。

我所说的解析是指找出元素在“class=""”属性或元素中可用的任何属性中的内容。还要找出元素内部的内容。这是我到目前为止搜索的地方:http://www.java2s.com/Code/Java/Development-Class/HTMLDocumentElementIteratorExample.htm

关于这方面我发现的很少。

我知道那里有很多 Java 解析器。我试过 JTidy 和默认的 Swing 解析器。我更愿意使用内置到 java 的解析器。

这是我到目前为止所拥有的(这只是测试其工作原理的方法,当我知道什么以及如何使用时,就会出现正确的代码。此外,连接是一个 URLConnection 变量,并且在调用此方法之前已经建立了连接。 <只是为了澄清):

public void parse() {
        try {

            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            // copied from http://www.java2s.com/Code/Java/Development-Class/HTMLDocumentElementIteratorExample.htm
            HTMLEditorKit htmlKit = new HTMLEditorKit();
            HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
            HTMLEditorKit.Parser parser = new ParserDelegator();
            HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
            parser.parse(br, callback, true);

            // Parse
            ElementIterator iterator = new ElementIterator(htmlDoc);
            Element element;

            while ((element = iterator.next()) != null) {
                AttributeSet attributes = element.getAttributes();

                Object name = attributes.getAttribute(StyleConstants.NameAttribute);
                System.out.println ("All attrs of " + name + ": " + attributes.getAttributeNames().toString());
                Enumeration e = attributes.getAttributeNames();
                Object obj;
                while (e.hasMoreElements()) {
                    obj = e.nextElement();
                    System.out.println (obj.toString());
                    System.out.println ("attribute of class = " + attributes.containsAttribute("class", "login"));
                }

                if ((name instanceof HTML.Tag)
                        && ((name == HTML.Tag.H1) || (name == HTML.Tag.H2) || (name == HTML.Tag.H3))) {
                    // Build up content text as it may be within multiple elements
                    StringBuffer text = new StringBuffer();
                    int count = element.getElementCount();
                    for (int i = 0; i < count; i++) {
                        Element child = element.getElement(i);
                        AttributeSet childAttributes = child.getAttributes();
                        if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                            int startOffset = child.getStartOffset();
                            int endOffset = child.getEndOffset();
                            int length = endOffset - startOffset;
                            text.append(htmlDoc.getText(startOffset, length));
                        }
                    }
                    System.out.println(name + ": " + text.toString());
                }
            }
        } catch (IOException e) {
            System.out.println ("Exception?1 " + e.getMessage() );
        } catch (Exception e) {
            System.out.println ("Exception? " + e.getMessage());
        }
    }

问题是:如何获取任何元素的属性并将它们打印出来?

最佳答案

这段代码不必要地冗长。我建议使用更好的库,如 Jsoup .下面是一些代码,用于查找此页面上所有 div 的所有属性。

String url = "http://stackoverflow.com/questions/7311269"
             + "/java-print-any-detail-of-html-element";
Document doc = Jsoup.connect(url).get();
Elements divs = doc.select("div");
int i = 0;
for (Element div : divs) {
    System.out.format("Div #%d:\n", ++i);
    for(Attribute attr : div.attributes()) {
        System.out.format("%s = %s\n", attr.getKey(), attr.getValue());
    }
}

关注Jsoup Cookbook详细介绍这个强大的库。

关于Java - 打印 HTML 元素的任何细节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7311269/

相关文章:

php - 忽略 preg_replace 中的 img 标签

java - Java 堆转储中的统计信息分割是什么

java - 在带有数据库数据的列表中使用线程

java - java 文本区域错误

javascript - 在 Javascript 中从 HTML 中提取文本的更好方法

python - BeautifulSoup HTML 表格解析

java - 为什么 `exception` 在任何地方都看不到?

java - lucene中为不同的查询词分配不同的权重

Java:如何使 JSpinner 显示具有一定偏移量的值

java - 将 HTML 和 CSS 样式应用于 Java Swing 组件