iphone:解析html的第三库hpple初试

今天搞了一天,想用hpple较为便利的利用xpath解析html。

参考的是这里面的做法:http://lwxshow.com/ios-iphone-development-teaches-you-how-to-use-the-objective-c-parsing-html-lwxshow-com

(相关:

    http://stackoverflow.com/questions/405749/parsing-html-on-the-iphone 

           http://stackoverflow.com/questions/9746745/xpath-attributes-selection

它里面说的挺详细的:就是引用 https://github.com/topfunky/hpple 上的hpple库,再结合libxml,就可以使用xpath搜索html了。

关于xpath的可以参考:w3school的教程 http://www.w3school.com.cn/xpath/index.asp

相关配置好了之后就可以直接使用:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSError *error;
    
    NSData *htmlData = [[NSString stringWithContentsOfURL:[NSURL
                                                           URLWithString: @"http://dict.youdao.com/m/search?keyfrom=dict.mindex&vendor=&q=apple"]
                                                 encoding:NSASCIIStringEncoding error:&error]
                        dataUsingEncoding:NSUTF8StringEncoding];
    TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
    NSArray *elements  = [xpathParser searchWithXPathQuery:@"//title"]; // get the title
    NSLog(@"%d",[elements count]);
    TFHppleElement *element = [elements objectAtIndex:0];
    
    NSString *content = [element content];
    NSString *tagname = [element tagName];
    NSString *attr = [element objectForKey:@"href"];
    NSLog(@"content = %@",content);
    NSLog(@"tagname = %@",tagname);
    NSLog(@"attr is = %@",attr);
}

使用工程应该是这样,这种方法的确可以较快找到相应的节点,只要你对xpath的规则熟悉。

但是不知道哪里出了错误,我的content一直显示不出来,但是相应的节点是对的,因为其属性都可以抓得到。找了好多都不知道原因,如果知道的,麻烦留言告知!

   


作者:老Zhan
出处:http://www.cnblogs.com/mybkn/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 
原文地址:https://www.cnblogs.com/mybkn/p/2610472.html