【问题标题】:Java - Print any detail of HTML elementJava - 打印 HTML 元素的任何细节
【发布时间】:2011-11-10 19:04:40
【问题描述】:

我对 Java 相当陌生,至少在与 Web 交互方面。无论如何,我正在制作一个必须从网页中抓取 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());
        }
    }

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

【问题讨论】:

  • 抱歉,您有什么问题?
  • 如何找出有哪些元素,例如class 属性和其中的内容,以及如何找出元素内部的内容(这部分在代码中完成,对其进行小的修改就可以了,但我仍然坚持属性)。或者如果 HTML 中的特定元素具有此属性。再次,问题:如何找出一个元素有什么属性。谢谢
  • 如果您需要一个易于使用的灵活 Java HTML 解析器,请下载并使用 JSoup。不要尝试自己滚动,并且没有 Java 的“内置 Java”HTML 解析器。
  • 您可以使用 XML DOM api 来解析 HTML,您可以轻松地获得属性列表。见download.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/…
  • @Daniel:只有当你能保证 HTML 完全符合 XML 标准时才会起作用,这就是 JTidy 的亮点,因为我相信它就是这样做的。

标签: java swing html-parsing


【解决方案1】:

此代码不必要地冗长。我建议使用更好的库,例如 Jsoup。这里有一些代码可以找出这个页面上所有divs的所有属性。

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,了解这个强大的库。

【讨论】:

  • amen 和 1+ 为您提供适当的答案——来自另一个 JSoup 粉丝。
  • Jsoup 似乎真的明白我想要什么。谢谢。还在玩代码;)
  • 天哪。如果我有能力给你一百万票,我会的,因为你只是为我节省了几个小时的工作时间。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 2023-02-25
相关资源
最近更新 更多