现在的位置: 首页 > 综合 > 正文

ASIHTTPRequest+TFHpple

2018年01月08日 ⁄ 综合 ⁄ 共 1872字 ⁄ 字号 评论关闭

转载请注明出处:http://blog.csdn.net/horkychen

作为一个iOS练习,使用ASIHTTPRequest+TFHpple写了个小程序读取CSDN博客的已读等信息微笑。其中ASIHTTPRequest负责发送HTTP
Request以获取博客主页,然后使用
TFHpple (XPath)解析出指定的HTML元素,然后读取相关的信息。

注意,关于两个库的使用,已经有不少资料了。其中TFHpple会使用search这个方法,现在要使用searchWithXPathQuery替换。

 

中间遇到的问题就是XPath的撰写。除了上W3CSchool读一个课程,还可以从Chrome WebStoe下一个XPath的插件,很好。

然后当目标网页加载完后, 点击一个元素就可以看到它的xpath,非常方便!

给出了多个项目,选择一个就可以了。 不过,可能不能直接使用(比如第2项的*号并不是所有的XPath library都能支持)。可以再配合FirePath测试一下:

(或许Chrome有其它插件,我手上刚好有FirePath就用它了!)

 

剩下的事情就简单了。下面贴出来主要的代码做为参考:

  1. -(IBAction )onConnect: (id)sender;  
  2. {  
  3.     NSURL *url = nil;  
  4.     if ([[mURLTexttext] length]<=0)   
  5.     {  
  6.             url = [ NSURLURLWithString : @"http://blog.csdn.net/horkychen"];  
  7.     }  
  8.     else   
  9.     {  
  10.             url = [ NSURLURLWithString : [mURLTexttext]];  
  11.     }  
  12.         ASIHTTPRequest *request = [ ASIHTTPRequestrequestWithURL :url];  
  13.     [request startSynchronous ];  
  14.     NSError *error = [request error ];  
  15.     assert (!error);  
  16.     NSString *response = [request responseString ];  
  17.     NSLog ( @"%@" ,response);  
  18.     [selfparseTheData:response];  
  19. }  
  20.   
  21. -(void)parseTheData:(NSString*)URLString  
  22. {  
  23.     NSData *htmlData = [[URLString dataUsingEncoding:NSUTF8StringEncoding] retain];  
  24.     TFHpple *xpathParser = [[TFHpplealloc] initWithHTMLData:htmlData];  
  25.     NSArray *elements  = [xpathParser searchWithXPathQuery:@"//ul[@id='blog_rank']/li/span/text()"];   
  26.      //    //html/body/div[2]/div[3]/div[2]/div/div/ul[2]/ul/li/span   
  27.      //    //ul[@id='blog_rank']/li/span/text()  
  28.         for(int i=0;i<[elements count];i++)  
  29.     {  
  30.         TFHppleElement *element = [elements objectAtIndex:i];  
  31.         NSString *myTitle = [element content];  
  32.                 NSLog(@"%@", myTitle);  
  33.                 if ( 0==i )  
  34.         {  
  35.             [mCounterLblsetText:myTitle];  
  36.         }  
  37.     }  
  38.         [xpathParser release];  
  39.     [htmlData release];  
  40. }
     

抱歉!评论已关闭.