【问题标题】:Programatically obtaining a list from HTML using HtmlUnit使用 HtmlUnit 以编程方式从 HTML 获取列表
【发布时间】:2013-01-16 04:51:09
【问题描述】:

我正在尝试以编程方式(在 Java 中)提取与特定日期相对应的文章列表(标题和 URL 链接),如 here 所示。

结果会是这样的:

Thursday, January 31, 2013

 - Dollar Curbs Tumble Despite....
 - http://finance.yahoo.com/news/dollar-curbs-tumble-despite-gdp-051100047.html

Wednesday, January 30,2013

 - [video] Santelli's Midday Bond Report
 - http://us.rd.yahoo.com/finance/external/video/cnbc/SIG=110mfa5qs/*http://video.cnbc.com/gallery/?video=3000144631&__source=yahoo%7Cheadline%7Cquote%7Cvideo%7C&par=yahoo

因此,如图所示,对于给定的日期,我正在尝试使用 HtmlUnit 提取所有标题/链接。

问题是:对于这项琐碎的任务,我对 HTML/DOM 的了解非常有限,如果有人能帮助我解决这个问题或为我指明正确的方向,我将不胜感激。

谢谢。

编辑: 检查页面时,似乎我正在寻找的标签包含在交替的“h3”和“ul”标签中。我只是不知道如何获取和遍历这些标签..

【问题讨论】:

    标签: java html dom htmlunit


    【解决方案1】:
    【解决方案2】:

    首先,查找 id 为“yfncsumtab”的表:

    HtmlTable table = page.getElementById("yfncsumtab");
    

    然后,在表中查找 <h3><ul>

    SimpleDateFormatter dateParser = ...
    List<DateAndTitle> result = new LinkedList();
    Date lastDate = null;
    
    // for(HtmlElement node : table.getHtmlElementDescendants()) {
    for(HtmlElement node : findAllChildren(table)) {
        if( "ul".equals( node.getTagName() ) ) {
            String title = node.asText();
            result.add(new DateAndTitle(lastDate, title);
        }
        if( "h3".equals( node.getTagName() ) ) {
            String dateString = node.asText();
            lastDate = dateParser.parse(dateString);
        }
    }
    

    和帮助函数递归查找所有后代 html 节点:

    private HtmlElement findAllChildren(DomNode parent) {
        List<HtmlElement> result = new LinkedList();
        for(DomNode child : parent.getChildren()) {
            if( child instanceof HtmlElement ) {
                result.add( (HtmlElement) child );
            }
        }
    
        for(DomNode child : parent.getChildren) {
            result.addAll( findAllChildren( child ) );
        }
    
        retutn result;
    }
    

    【讨论】:

    【解决方案3】:

    只要学习XPath。使用 getFirstByXPathgetByXPath,您将获得 1 到 4 行的解决方案。它在Getting Started 页面中。

    【讨论】:

      猜你喜欢
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多