编码 data:text/html;c,iOS 用TFHpple抓取GB-2312编码的html页面,页面返回编码错误
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
具體的方法可以參考:(英文網址介紹)http://stackoverflow.com/questions/405749/parsing-html-on-the-iphone
(中文網址介紹)http://blog.csdn.net/xiaoxuan415315/article/details/7788955;還要代碼下載,不過里面有錯
Objective c代碼
NSData?*htmlData?=?[NSString?stringWithContentsOfFile:[NSURL?URLWithString:@"http://www.baidu.com"]?encoding:NSUTF8StringEncoding?error:nil];
會報:[NSURL getFileSystemRepresentation:maxLength:]: unrecognized selector sent to instance 0x6bcad20
Objective c代碼
NSData?*htmlData??=?[NSString?stringWithContentsOfURL:[NSURL?URLWithString:@"http://www.baidu.com"]?encoding:NSUTF8StringEncoding?error:nil];
匹配還是有問題
應該這個更合適點
Objective c代碼
NSData?*htmlData?=?[NSData?dataWithContentsOfURL:[NSURL?URLWithString:@"http://www.baidu.com"]];
下面講一下我自己實現的過程中的關鍵代碼:
解析非utf-8頁面的思路 :
把網絡流返回的NSDate的GB2312(假設是這個)轉換成TFHpple能正確解析的UTF-8編碼的NSData;
將其中一行的轉換成UTF-8形式的
可以采用如下兩種方案解決:
方法一:
Objective c代碼
//轉換成GBK編碼
NSStringEncoding?gbEncoding?=?CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSData?*htmlData?=?[NSData?dataWithContentsOfURL:[NSURL?URLWithString:@"可以是非utf-8的網頁"]];
NSString?*htmlStr?=?[[[NSString?alloc]?initWithData:htmlData?encoding:gbEncoding]?autorelease];
方法二:
Objective c代碼
NSData?*htmlData?=?[NSData?dataWithContentsOfURL:[NSURL?URLWithString:@"可以是非utf-8的網頁"]];
CFStringRef?bgCFStr?=?CFStringCreateWithBytes(NULL,?[htmlData?bytes],?[htmlData?length],?kCFStringEncodingGB_18030_2000,?false);
NSString?*gbHtmlStr?=?(NSString?*)bgCFStr;
方法一或者二選其一,然后加下面的代碼就可以實現簡單解析了
Objective c代碼
NSString?*utf8HtmlStr?=?[htmlStr?stringByReplacingOccurrencesOfString:@""
withString:@""];
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 = [htmlStrdataUsingEncoding:NSUTF8StringEncoding];
NSString?--》NSData
NSString*htmlStr = [[[NSStringalloc]initWithData:htmlDataencoding:NSUTF8StringEncoding]autorelease];
總結
以上是生活随笔為你收集整理的编码 data:text/html;c,iOS 用TFHpple抓取GB-2312编码的html页面,页面返回编码错误的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html表单和输入方法,HTML 表单和
- 下一篇: 计算机科学与技术在线阅读,TL2011计