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

编写小程序查看CSDN博客信息(ASIHTTPRequest+TFHpple)

2013年05月06日 ⁄ 综合 ⁄ 共 1479字 ⁄ 字号 评论关闭

转载请注明出处: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就用它了!)

 

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

-(IBAction )onConnect: (id)sender;
{
    NSURL *url = nil;
    if ([[mURLTexttext] length]<=0) 
    {
            url = [ NSURLURLWithString : @"http://blog.csdn.net/horkychen"];
    }
    else 
    {
            url = [ NSURLURLWithString : [mURLTexttext]];
    }
        ASIHTTPRequest *request = [ ASIHTTPRequestrequestWithURL :url];
    [request startSynchronous ];
    NSError *error = [request error ];
    assert (!error);
    NSString *response = [request responseString ];
    NSLog ( @"%@" ,response);
    [selfparseTheData:response];
}

-(void)parseTheData:(NSString*)URLString
{
    NSData *htmlData = [[URLString dataUsingEncoding:NSUTF8StringEncoding] retain];
    TFHpple *xpathParser = [[TFHpplealloc] initWithHTMLData:htmlData];
    NSArray *elements  = [xpathParser searchWithXPathQuery:@"//ul[@id='blog_rank']/li/span/text()"]; 
     //    //html/body/div[2]/div[3]/div[2]/div/div/ul[2]/ul/li/span 
     //    //ul[@id='blog_rank']/li/span/text()
        for(int i=0;i<[elements count];i++)
    {
        TFHppleElement *element = [elements objectAtIndex:i];
        NSString *myTitle = [element content];
                NSLog(@"%@", myTitle);
                if ( 0==i )
        {
            [mCounterLblsetText:myTitle];
        }
    }
        [xpathParser release];
    [htmlData release];
}


 

 

抱歉!评论已关闭.