在一些情况下我们在工程中需要解析html中的数据,TFHpple是一个非常方便的三方类.它可以根据标签解析html数据,应用比较简便.
首先要先做一下准备工作。
下载TFHpple:,将文件夹拖入到工程中.
TFHpple的工作原理是事先根据URL将html数据转化为NSData类型.然后再根据标签解析数据.
- (void)viewDidLoad
{
NSString *str = [NSString stringWithFormat:@BrandDisplayDetailURL, self.brandId];
NSLog(@"%@" , str);
NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:str]];
[self handelHTML:data];
}
#pragma mark - 解析html
- (void) handelHTML:(NSData *)data
{
TFHpple *xpathParser = [[TFHpple alloc]initWithHTMLData:data];
NSMutableArray *arr = [xpathParser searchWithXPathQuery:@"//a"].mutableCopy;
NSMutableArray *arrMark = [xpathParser searchWithXPathQuery:@"//mark"].mutableCopy;
NSMutableArray *arrPrice = [xpathParser searchWithXPathQuery:@"//span"].mutableCopy;
NSMutableArray *arrPicURL = [xpathParser searchWithXPathQuery:@"//img"].mutableCopy;
for (NSInteger i = 0; i<arr.count; i++) {
TFHppleElement *hpple = arr[i];
if (hpple.text != nil && ![hpple.text isEqualToString:@"查看更多..."]) {
[self.titleArr addObject:hpple.text];
}else{
NSDictionary *dic = hpple.attributes;
if (![[dic objectForKey:@"href"] isEqualToString:@"javascript:getData()"]) {
NSString *str = [dic objectForKey:@"href"];
NSArray *divArr = [str componentsSeparatedByString:@":"];
[self.popID addObject:divArr[2]];
}
}
}
for (NSInteger i = 0; i < arrMark.count; i++) {
TFHppleElement *hpple = arrMark[i];
if (hpple.text != nil) {
[self.markArr addObject:hpple.text];
}
}
for (NSInteger i = 0; i < arrPrice.count; i++) {
TFHppleElement *hpple = arrPrice[i];
if (hpple.text != nil) {
[self.priceArr addObject:hpple.text];
}
}
for (NSInteger i = 0; i < arrPicURL.count; i++) {
TFHppleElement *hpple = arrPicURL[i];
NSDictionary *dic = hpple.attributes;
[self.picURLArr addObject:[dic objectForKey:@"date-src"]];
}
[self.brandDetailTableView reloadData];
}
需要注意的是.从标签解析出来的数据是用数组存储的,而数组中存储的是TFHppleElement类型的对象.如果要完全取出数据.则需要使用TFHppleElement对象的属性.主要有text(取出文本),raw(取出标签所有内容),attributes(取出标签所包含的属性,返回值是字典),children(取出标签下所有子标签,返回数组).
其实,TFHpple的使用还是比较简单,html解析难在分析html的标签上.如果想要取的数据标签嵌套的比较复杂,想要取出来非常的费工夫.在这种情况下,首选的还应该是webView.