通过url,获取html内容,并解析

来源:互联网 发布:古巴没有网络 编辑:程序博客网 时间:2024/05/03 14:12
  1. 1、第一种获取方式 :通过过stringWithContentsOfURL获取  
  2.  NSString *urlstring= [NSString stringWithFormat:@"http://baidu.com/=%@",string1];// 此处网址不对,只是示意可以生成一个动态的urlstring  
  3.  //抓取网页中 网释义内容  
  4.     NSString * encodedString1 = (NSString *)CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)urlstring, NULL, NULL,  kCFStringEncodingUTF8 );  
  5.     NSURL *url1 = [NSURL URLWithString:encodedString1];  
  6.     NSString *retStr = [NSString stringWithContentsOfURL:url1 encoding:NSUTF8StringEncoding error:nil];//[[NSString alloc] initWithData:data encoding:];  
  7.     NSLog(@" html = %@",retStr);  
  8.   
  9. 上述方式获取的内容时有一个弊端,当网络不是太好时,会阻塞在stringWithContentsOfURL这里,导致程序假死,(可以通过创建一个线程的方式,来获取数据,这样不好阻塞主线程),或者你可以使用第二种方式:  
  10.   
  11. 2、第二种方式:通过NSURLConnection获取//获取指定网页的内容  
[csharp] view plain copy
  1.  NSString *urlString= [NSStringstringWithFormat:@"http://baidu.com"];  
  2.     NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString,NULL, NULL, kCFStringEncodingUTF8 );  
  3.     NSURL *url =[NSURLURLWithString:encodedString];  
  4.     NSMutableURLRequest *req=[[NSMutableURLRequestalloc]   
  5.                               initWithURL:url   
  6.                               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData   
  7.                               timeoutInterval:30.0];  
  8.     
  9. receivedData=[[NSMutableDataalloc] initWithData:nil];//接受数据  
  10.     [req setHTTPMethod: @"POST"];  
  11.     NSURLConnection *connection = [[NSURLConnectionalloc] initWithRequest:req delegate:self startImmediately:YES];  
  12.     [req release];  
  13.     [connection release];  
  14.   
  15. 在委托方法中接受数据,这种方式是异步的,不会阻塞当前线程,获取数据时,你可以做别的事情  
  16. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error  
  17. //简单错误处理  
  18.     UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"出错了"message:@"网络链接异常" delegate:nilcancelButtonTitle:@"OK" otherButtonTitles:nil];  
  19.     [alert show];  
  20.     [alert release];  
  21. }  
  22.   
  23. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  
  24. {  
  25.     [receivedData setLength:0];//置空数据  
  26.       
  27. }  
  28.   
  29. //接收NSData数据  
  30. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data   
  31. {  
  32.     [receivedData appendData:data];  
  33. }  
  34.   
  35. //接收完毕,显示结果  
  36. - (void)connectionDidFinishLoading:(NSURLConnection *)connection   
  37. {  
  38.     [connection cancel];  
  39.     NSString *results = [[NSStringalloc]   
  40.                          initWithBytes:[receivedDatabytes]   
  41.                          length:[receivedDatalength]   
  42.                          encoding:NSUTF8StringEncoding];// 注意数据编码方式,选中正确的编码方式,防止乱码  
  43.     [selfloadingNetDescription:results];  
  44.     [results release];  
  45. //    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"数据" message:@"下载完成" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];  
  46. //    [alert show];  
  47. //    [alert release];  
  48. //    NSLog(@"%@",results);  
  49. }     
  50.   
  51. 其实还有一种曲折的方式来获取url对应的网页内容,就是通过webView加载对应url,  
  52.  [mWebViewloadRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:encodedString]]];  
  53. 在其委托方法:  
  54. webViewDidFinishLoad中通过js来获取相应的网页内容;  
  55. 例如:NSString *allHTML = [wView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];  
  56. 更具体的可以参考:stringByEvaluatingJavaScriptFromString这个函数的用法  
  57.   
  58. 通过上面的方式获取到html数据后,就可以通过字符串的一些处理函数来获取自己像要的内容(当然你也可以用一些xml解析库来进行解析,此处,只简单介绍一下字符串的处理):  
  59. 简单实例://获取两个body之间的内容:htmlString为上面获取的html字符串  
  60.    NSRange range1 = [htmlString rangeOfString:@"<body>"];// 返回的location是<body>在htmlString中的起始位置,使用是注意  
  61.     NSRange range2 = [htmlString rangeOfString:@"</body>"];  
  62. if(range3.location !=NSNotFound && range3.length!=0)//简单的判断,不全,使用时注意补全  
  63.    {  
  64.         NSString* bodyString= [retStr substringWithRange:NSMakeRange(range1.location, range2.location-range1.location+range2.length)];  
  65. NSLog(@"%@"bodyString);  
  66. }  
[csharp] view plain copy
  1.   
[csharp] view plain copy
  1. 补充一些字符串常用处理函数:  
  2. 1、替换字符串  
  3.  //将数据中的“回车换行”换成网页中的回车符<br/>  
  4.     NSString *localString= [descriptionOne stringByReplacingOccurrencesOfString:@"\r\n" withString:@"<br/>"];  
  5.   
  6.  //从字符串开头一直截取到指定位置,但不包括该位置的字符  
  7. //            NSString *first =[string1 substringToIndex:range.location-1] ;   
  8. //            //从指定位置开始获取之后的所有字符(包括指定位置的字符)  
  9. //            NSString *last = [string1 substringFromIndex:range.location+1];  
  10. //            //按照所给位置,长度,任意的从字符串中截取子串  
  11. //            NSString *word  = [string1 substringWithRange:NSMakeRange(range.location-1, 1)];  
0 0
原创粉丝点击