【问题标题】:Getting last <p> tag of HTML document获取 HTML 文档的最后一个 <p> 标签
【发布时间】:2011-07-26 19:15:57
【问题描述】:

我有一个 HTML 文档,例如:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body style="font-family: Geneva; color: rgb(0, 0, 0); font-size: 12px; word-wrap: break-word; font-weight: normal; font-style: normal; text-decoration: none; ">
        <p style="font-family: LucidaGrande; color: rgb(51, 102, 204); margin-top: 6px; margin-bottom: 6px; word-wrap: break-word; font-weight: normal; font-style: normal; text-decoration: none; ">
            fdskl says: (6:50:04 AM)
        </p>
        <p style="font-family: Arial-ItalicMT; color: rgb(0, 0, 0); margin-left: 36px; margin-top: 6px; margin-bottom: 6px; word-wrap: break-word; font-weight: normal; font-style: normal; text-decoration: none; ">
            Hello
        </p>
        <p style="font-family: LucidaGrande; color: rgb(51, 102, 204); margin-top: 6px; margin-bottom: 6px; word-wrap: break-word; font-weight: normal; font-style: normal; text-decoration: none; ">
            fdskl says: (6:50:18 AM)
        </p>
        <p style="font-family: Arial-ItalicMT; color: rgb(0, 0, 0); margin-left: 36px; margin-top: 6px; margin-bottom: 6px; word-wrap: break-word; font-weight: normal; font-style: normal; text-decoration: none; ">
            How are you?
        </p>
    </body>
</html>

我想得到这个 HTML 的最后一个 p 标记中的任何内容。所以在这种情况下,它会是“你好吗?”。使用 Cocoa,我该怎么做? 谢谢!

【问题讨论】:

    标签: html objective-c xml cocoa nsxmlparser


    【解决方案1】:

    您最好的选择是使用NSXMLDocument:

    NSData *htmlData = ... // get the html data, preferably asynchronously
    NSXMLDocument *document = [[[NSXMLDocument alloc] initWithData:htmlData options:NSXMLDocumentTidyHTML error:NULL] autorelease]; 
    NSArray *nodes = [document nodesForXPath:@"//body/p" error:NULL];
    NSXMLNode *lastP = [nodes lastObject];
    NSLog(@"%@", [lastP stringValue]);
    

    如果您希望代码更健壮,还应该检查错误而不是传递 NULL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 2016-01-17
      • 2015-03-25
      • 2011-06-10
      • 1970-01-01
      • 2018-06-18
      相关资源
      最近更新 更多