HTMLParser方法可以参考 https://github.com/zootreeves/Objective-C-HMTL-Parser
TFHpple方法的使用可以看https://github.com/topfunky/hpple
TFHpple,因为它很简单,也好用,但是它的功能不是很完完善。比如,不能获取children node。它是用XPath来定位和解析html或者xml。
xpath教程:http://www.w3school.com.cn/xpath/index.asp
具体的方法可以参考:(英文网址介绍)http://stackoverflow.com/questions/405749/parsing-html-on-the-iphone
(中文网址介绍)http://blog.youkuaiyun.com/xiaoxuan415315/article/details/7788955;还要代码下载,不过里面有错
- <span>NSData*htmlData=[NSStringstringWithContentsOfFile:[NSURLURLWithString:@"http://www.baidu.com</span>"]encoding:NSUTF8StringEncodingerror:nil];
会报:[NSURL getFileSystemRepresentation:maxLength:]: unrecognized selector sent to instance 0x6bcad20
- NSData*htmlData=[NSStringstringWithContentsOfURL:[NSURLURLWithString:@"http://www.baidu.com"]encoding:NSUTF8StringEncodingerror:nil];
匹配还是有问题
应该这个更合适点
- <span>NSData*htmlData=[NSDatadataWithContentsOfURL:[NSURLURLWithString:@"http://www.baidu.com
- </span>"]];
下面讲一下我自己实现的过程中的关键代码:
解析非utf-8页面的思路 :
- 把网络流返回的NSDate的GB2312(假设是这个)转换成TFHpple能正确解析的UTF-8编码的NSData;
- 将其中一行的<meta http-equiv="Content-Type" content="text/html; charset=gb2312">转换成UTF-8形式的
可以采用如下两种方案解决:
方法一:
- //转换成GBK编码
- NSStringEncodinggbEncoding=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
- NSData*htmlData=[NSDatadataWithContentsOfURL:[NSURLURLWithString:@"可以是非utf-8的网页"]];
- NSString*htmlStr=[[[NSStringalloc]initWithData:htmlDataencoding:gbEncoding]autorelease];
方法二:
- NSData*htmlData=[NSDatadataWithContentsOfURL:[NSURLURLWithString:@"可以是非utf-8的网页"]];
- CFStringRefbgCFStr=CFStringCreateWithBytes(NULL,[htmlDatabytes],[htmlDatalength],kCFStringEncodingGB_18030_2000,false);
- NSString*gbHtmlStr=(NSString*)bgCFStr;
方法一或者二选其一,然后加下面的代码就可以实现简单解析了
- NSString*utf8HtmlStr=[htmlStrstringByReplacingOccurrencesOfString:@"<metahttp-equiv=\"Content-Type\"content=\"text/html;charset=gb2312\">"
- withString:@"<metahttp-equiv=\"Content-Type\"content=\"text/html;charset=utf-8\">"];
- NSData*htmlDataUTF8=[utf8HtmlStrdataUsingEncoding:NSUTF8StringEncoding];
- TFHpple*xpathParser=[[TFHpplealloc]initWithHTMLData:htmlDataUTF8];
- NSArray*elements=[xpathParsersearch:@"//option"];
- TFHppleElement*element=[elementsobjectAtIndex:0];
- NSString*h3Tag=[elementcontent];
- NSLog(@"%@",h3Tag);
- mLabel.text=h3Tag;
- [xpathParserrelease];
- [htmlDatarelease];
很有用的网址:http://www.raywenderlich.com/14172/how-to-parse-html-on-ios
碰到的问题:NSData --》NSString
NSData*htmlData = [htmlStrdataUsingEncoding:NSUTF8StringEncoding];
NSString--》NSData
NSString*htmlStr = [[[NSStringalloc]initWithData:htmlDataencoding:NSUTF8StringEncoding]autorelease];