编码 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,因?yàn)樗芎?jiǎn)單,也好用,但是它的功能不是很完完善。比如,不能獲取children node。它是用XPath來(lái)定位和解析html或者xml。
hpple解析html中可能存在的問(wèn)題:http://www.ccbase.net/post/66.html
具體的方法可以參考:(英文網(wǎng)址介紹)http://stackoverflow.com/questions/405749/parsing-html-on-the-iphone
(中文網(wǎng)址介紹)http://blog.csdn.net/xiaoxuan415315/article/details/7788955;還要代碼下載,不過(guò)里面有錯(cuò)
Objective c代碼
NSData?*htmlData?=?[NSString?stringWithContentsOfFile:[NSURL?URLWithString:@"http://www.baidu.com"]?encoding:NSUTF8StringEncoding?error:nil];
會(huì)報(bào):[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];
匹配還是有問(wèn)題
應(yīng)該這個(gè)更合適點(diǎn)
Objective c代碼
NSData?*htmlData?=?[NSData?dataWithContentsOfURL:[NSURL?URLWithString:@"http://www.baidu.com"]];
下面講一下我自己實(shí)現(xiàn)的過(guò)程中的關(guān)鍵代碼:
解析非utf-8頁(yè)面的思路 :
把網(wǎng)絡(luò)流返回的NSDate的GB2312(假設(shè)是這個(gè))轉(zhuǎn)換成TFHpple能正確解析的UTF-8編碼的NSData;
將其中一行的轉(zhuǎn)換成UTF-8形式的
可以采用如下兩種方案解決:
方法一:
Objective c代碼
//轉(zhuǎn)換成GBK編碼
NSStringEncoding?gbEncoding?=?CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSData?*htmlData?=?[NSData?dataWithContentsOfURL:[NSURL?URLWithString:@"可以是非utf-8的網(wǎng)頁(yè)"]];
NSString?*htmlStr?=?[[[NSString?alloc]?initWithData:htmlData?encoding:gbEncoding]?autorelease];
方法二:
Objective c代碼
NSData?*htmlData?=?[NSData?dataWithContentsOfURL:[NSURL?URLWithString:@"可以是非utf-8的網(wǎng)頁(yè)"]];
CFStringRef?bgCFStr?=?CFStringCreateWithBytes(NULL,?[htmlData?bytes],?[htmlData?length],?kCFStringEncodingGB_18030_2000,?false);
NSString?*gbHtmlStr?=?(NSString?*)bgCFStr;
方法一或者二選其一,然后加下面的代碼就可以實(shí)現(xiàn)簡(jiǎn)單解析了
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];
很有用的網(wǎng)址:http://www.raywenderlich.com/14172/how-to-parse-html-on-ios
碰到的問(wèn)題:NSData --》NSString
NSData*htmlData = [htmlStrdataUsingEncoding:NSUTF8StringEncoding];
NSString?--》NSData
NSString*htmlStr = [[[NSStringalloc]initWithData:htmlDataencoding:NSUTF8StringEncoding]autorelease];
總結(jié)
以上是生活随笔為你收集整理的编码 data:text/html;c,iOS 用TFHpple抓取GB-2312编码的html页面,页面返回编码错误的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: html表单和输入方法,HTML 表单和
- 下一篇: 计算机科学与技术在线阅读,TL2011计