Objective-C解析HTML!

移动开发 iOS
xml,json都有大量的库来解析,我们如何解析html呢? TFHpple是一个小型的封装,可以用来解析html,它是对libxml的封装,语法是xpath。 今天我看到一个直接用libxml来解析html。

使用Objective-C解析HTML或者XML,系统自带有两种方式一个是通过libxml,一个是通过NSXMLParser。不过这两种方式都需要自己写很多编码来处理抓取下来的内容,而且不是很直观。
有一个比较好的类库hpple,它是一个轻量级的包装框架,可以很好的解决这个问题 。它是用XPath来定位和解析HTML或者XML。
安装步骤:
-加入 libxml2 到你的项目中
   Menu Project->Edit Project Settings
   搜索 “Header Search Paths”
   添加新的 search path “${SDKROOT}/usr/include/libxml2″
   Enable recursive option
-加入 libxml2 library 到你的项目
   Menu Project->Edit Project Settings
   搜索 “Other Linker Flags”
   添加新的 search flag “-lxml2″
-将下面hpple的源代码 加入到你的项目中:
HTFpple.h
HTFpple.m
HTFppleElement.h
HTFppleElement.m
XPathQuery.h
XPathQuery.m
-XPath学习地址http://www.w3schools.com/XPath/default.asp 
示例代码:

  1. #import "TFHpple.h" 
  2. NSData *data = [[NSData alloc] initWithContentsOfFile:@"example.html"]; 
  3. // Create parser 
  4. xpathParser = [[TFHpple alloc] initWithHTMLData:data]; 
  5. //Get all the cells of the 2nd row of the 3rd table  
  6. NSArray *elements  = [xpathParser search:@"//table[3]/tr[2]/td"]; 
  7. // Access the first cell 
  8. TFHppleElement *element = [elements objectAtIndex:0]; 
  9. // Get the text within the cell tag 
  10. NSString *content = [element content];   
  11. [xpathParser release]; 
  12. [data release]; 

下载 地址:https://github.com/topfunky/hpple 

另外,还有一个类似的解决方案可以参考
ElementParser http://github.com/Objective3/ElementParser

 

源码下载:http://down.51cto.com/data/616107

 
责任编辑:闫佳明 来源: oschina
相关推荐

2011-08-10 18:07:29

Objective-C反射

2011-08-04 15:52:48

Objective-C HTML

2011-08-05 15:46:32

Objective-C 程序设计

2011-08-11 17:39:25

Objective-C笔试题

2011-07-29 16:08:31

Objective-C 内存

2011-08-15 14:02:36

Objective-C

2011-05-11 15:58:34

Objective-C

2011-05-11 11:20:26

Objective-C

2013-06-20 10:40:32

Objective-C实现截图

2012-06-15 09:47:48

Objective-CCategory

2014-06-25 14:02:59

Objective-CKVO

2012-03-07 13:43:59

Objective-C

2011-08-04 09:35:09

Objective-C 编码规范

2014-04-30 10:16:04

Objective-CiOS语法

2011-07-08 13:49:46

Objective-C UUID

2011-07-29 16:16:30

Objective-c block

2011-08-17 10:58:59

Objective-C构造函数

2011-08-03 16:55:05

Objective-C 代理

2011-08-04 14:58:37

Objective-C Cocoa NSString

2011-08-02 13:16:36

Objective-C 语法 函数
点赞
收藏

51CTO技术栈公众号