从字符串iPhone提取HTML属性



我有一个html字符串,我从一个网站的响应。我在那里做的每件事都很棒,我没有任何困难。我需要做的是在html中抓取only href属性。获取包含在该属性中的URL的最佳方法是什么?我是开放的任何外部图书馆,如果这是必要的,我只是想最有效的方式可能。谢谢。

使用此API解析HTML代码并选择所需的元素。

ElementParser是一个轻量级框架,可以方便地访问xml和html内容。与其迷失在HTML和XML规范的复杂性中,不如不掩盖它们本质上的简单性。它不会做所有的事情,它渴望做"刚刚好"。

来源:http://touchtank.wordpress.com/element-parser/


下面是如何在您自己的示例中使用ElementParser的示例。我希望这对你有帮助。

圣诞快乐!Ho-Ho-Ho

// Here you create the parser, don't forget to #import "Element.h" and #import "ElementParser.h"
ElementParser * parser = [[ElementParser alloc] init];
// This is the HTML source code that you want to parse
DocumentRoot* document = [parser parseHTML:@"<html><a href="http://google.com">Google Link</a></html>"];
// Create an array where you will put all the <a></a> elements
NSArray* elements = [document selectElements: @"a"];
// Iterate though the array, for each element pick the "href" attribute
NSMutableArray* results = [NSMutableArray array];
for (Element* element in elements){
    NSString* snipet = [element attribute:@"href"];
    // Add the result for each element to the "results" array
    [results addObject: snipet];
}
// Print the results on the screen
NSLog(@"%@",[results componentsJoinedByString: @"n"]);

你可以使用nsregulareexpression来提取html标签的url。

NSString *regexStr = @"http?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?";
NSString * url = @"<a href="http://www.stackoverflow.org/">stackoverflow</a>";
NSError *error;
NSRegularExpression *testRegex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error];
if( testRegex == nil ) NSLog( @"Error making regex: %@", error );
NSRange range = [testRegex rangeOfFirstMatchInString:url options:0 range:NSMakeRange(0, [url length])];
NSString * href = [url substringWithRange:range];

请记住nsregulareexpression需要ios4或ios5。

最新更新