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一直显示不出来,但是相应的节点是对的,因为其属性都可以抓得到。找了好多都不知道原因,如果知道的,麻烦留言告知!

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值