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