1

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

结果将是这样的:

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”标签中。我只是不知道如何到达和遍历这些标签..

4

3 回答 3

1

首先,找到 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;
}
于 2013-02-01T03:08:17.760 回答
1

尝试使用 getElementsByTagName() 以便您可以获取所有 <LI>

http://httpunit.sourceforge.net/doc/api/com/meterware/httpunit/WebResponse.html#getElementsByTagName(java.lang.String)

于 2013-02-01T03:00:34.517 回答
1

只需学习XPathgetFirstByXPath通过使用或,您将获得 1 到 4 行的解决方案getByXPath。它位于“入门”页面中。

于 2013-02-02T14:00:19.817 回答