怎樣抓取網頁內容


如果給你一個網頁鏈接, 來抓取指定的內容, 比如豆瓣電影排行榜, 那要怎樣才能做到了?

其實網頁內容的結構很是類似於XML, 那么我們就可以用解析XML的方式來解析HTML, 不過兩者之間的差距還是很大的, 好了, 廢話不多說, 我們開始解析HTML。

那么解析XML的庫比較多, 這里選用libxml來解析, 因為libxml是c語言接口, 找了一個用objective-c包裝接口的庫-hpple, 它的地址是https://github.com/topfunky/hpple, 那么網頁用的是豆瓣電影排行榜, 地址是http://movie.douban.com/chart

接下來新建工程, 工程采用的ARC, 引進libxml2和hpple庫, 新建實體類movie, 完整的項目結構如下: 

NewImage

movie的實現如下, 這個是實體類, 根據抓取網頁的內容來定這個實體

movie.h 

@interface Movie : NSObject
@property(nonatomic, strong) NSString   *name;
@property(nonatomic, strong) NSString   *imageUrl;
@property(nonatomic, strong) NSString   *descrition;
@property(nonatomic, strong) NSString   *movieUrl;
@property(nonatomic) NSInteger  ratingNumber;
@property(nonatomic, strong) NSString   *comment;
@end

 

那么最重要的部分來了, 不管網頁的內容是什么, 我們得先需要獲取網頁的內容, 下面就是通過NSURLConnection來獲取整個網頁的內容。

- (void)loadHTMLContent
{
    NSString *movieUrl = MOVIE_URL;
    NSString *urlString = [movieUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    __weak ViewController *weak_self = self;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if (nil == error) {
//            NSString *retString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//            NSLog(@"%@", retString);
            [weak_self parserHTML:data];
        }
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    }];
}

 

這里只是簡單的獲取網頁內容, 一些HTTP和錯誤處理不在此文討論中, 所以這里的代碼比較簡單, 在上面的代碼中有個parserHTML:的方法, 就是來解析獲取的網頁內容, 在解析網頁內容之前, 先來扯下xpath。

假設一個簡單網頁內容如下:

<html>
  <head>
    <title>Some webpage</title>
  </head>
  <body>
    <p class=”normal”>This is the first paragraph</p>
    <p class=”special”>This is the second paragraph. <b>This is in bold.</b></p>
  </body> 
</html>

比如想得到title的內容,那么xpath表達就是/html/head/title。如果想得到class="special"節點內容,xpath就是/html/body/p[@class='special']。

所以只要找對了xpath, 就會得到相應的節點內容, 那么來看下用hpple解析HTML

 

- (void)parserHTML:(NSData *)data
{
    if (nil != data) {
        TFHpple *movieParser = [TFHpple hppleWithHTMLData:data];
        NSString *movieXpathQueryString = @"/html/body/div[@id='wrapper']/div[@id='content']/div[@class='grid-16-8 clearfix']/div[@class='article']/div[@class='indent']/table/tr/td/a[@class='nbg']";
        NSArray *movieNodes = [movieParser searchWithXPathQuery:movieXpathQueryString];
        
        for (TFHppleElement *element in movieNodes) {
            Movie *m = [[Movie alloc] init];
            m.name = [element objectForKey:@"title"];
            m.movieUrl = [element objectForKey:@"href"];
            
            for (TFHppleElement *child in element.children) {
                if ([child.tagName isEqualToString:@"img"]) {
                    @try {
                        m.imageUrl = [child objectForKey:@"src"];
                    }
                    @catch (NSException *exception) {
                        
                    }
                }
            }
            
            [self.movies addObject:m];
        }
        
        [self.movieTableView reloadData];
    }
}

 

代碼中首頁找到相應節點的路徑, 然后searchWithXPathQuery, 得到一個數組, 遍歷組織數據就能夠在table view中展示了。具體效果如下:

NewImage

好了, 網頁內容被抓取出來了, 具體的實際項目中都要比這個復雜, so, 這只是個引導的示例。

 

參考:http://www.raywenderlich.com/14172/how-to-parse-html-on-ios#

注: 本文由嘯寒原著,請支持原著!轉載請附上原文鏈接: http://www.cnblogs.com/xiaohan-wu/p/3203932.html

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM