iOS 开发UI的实现ios 常用第三方库的使用

iOS 数据解析之使用TFHpple解析html

2017-01-15  本文已影响2914人  DH_Fantasy

TFHpple是一个XML/HTML解析框架,我们可以用来解析从后台发送过来的HTML数据。
  如果要在项目中使用这个框架,首先需要将其导入,在这里使用CocoaPods将其导入。

下面是TFHpple的示例代码。

#import "TFHpple.h"

NSData  * data      = [NSData dataWithContentsOfFile:@"index.html"];

TFHpple * doc       = [[TFHpple alloc] initWithHTMLData:data];
NSArray * elements  = [doc search:@"//a[@class='sponsor']"];

TFHppleElement * element = [elements objectAtIndex:0];
[e text];                       // The text inside the HTML element (the content of the first text node)
[e tagName];                    // "a"
[e attributes];                 // NSDictionary of href, class, id, etc.
[e objectForKey:@"href"];       // Easy access to single attribute
[e firstChildWithTagName:@"b"]; // The first "b" child node

从中可以看出要解析HTML中的内容分四步:

接下来使用TFHpple解析http://www.jianshu.com/u/b05772019513中的数据,获取到每篇文章的标题。

标题

代码如下:

    NSString *url = @"http://www.jianshu.com/u/b05772019513";
    
    NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
    
    TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:data];
    
    NSArray *dataArr = [xpathParser searchWithXPathQuery:@"//a"];
    
    for (TFHppleElement *element in dataArr) {
        
        if ([[element objectForKey:@"class"] isEqualToString:@"title"]) {
            NSLog(@"%@",element.text);
            
        }
        
    }
解析结果

联系作者:简书·DH_Fantasy 新浪微博·DH_Fantasy
版权声明:自由转载-非商用-非衍生-保持署名(CC BY-NC-ND 3.0

上一篇下一篇

猜你喜欢

热点阅读