2012-08-14 72 views
0

我想要做的是解析網站上的頁面的多個部分。下面是我在做什麼:解析多個HTML分支hpple

NSURL *tutorialsUrl = [NSURL URLWithString:@"http://www.cetsp.com.br/"]; 
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl]; 

TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData]; 

NSArray *holder; 

NSString *tutorialsXpathQueryString = @"//div[@class='info oeste']/a/h4"; 
NSString *tutorialsXpathQueryString2 = @"//div[@class='info norte']/a/h4"; 
NSString *tutorialsXpathQueryString3 = @"//div[@class='info centro']/a/h4"; 
NSString *tutorialsXpathQueryString4 = @"//div[@class='info leste']/a/h4"; 
NSString *tutorialsXpathQueryString5 = @"//div[@class='info sul']/a/h4"; 

NSArray *oeste = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString]; 
NSArray *norte = [tutorialsParser searchWithXPathQuery: tutorialsXpathQueryString2]; 
NSArray *centro = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString3]; 
NSArray *leste = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString4]; 
NSArray *sul = [tutorialsParser searchWithXPathQuery: tutorialsXpathQueryString5]; 

holder = [[NSArray alloc] initWithObjects:norte, oeste, centro,leste,sul, nil]; 

for (NSArray *array in holder) { 

    for (TFHppleElement *element in array) { 

     NSLog([[element firstChild] content]); 
    } 
} 

控制檯日誌5種不同的正確的結果,但你可以看到我的代碼是相當繁瑣的。那麼如何獲得多個標籤的所有內容?

謝謝!

回答

5

Hpple使用XPathQuery來解析HTML。如果你想搜索任何類,你可以使用:

@"//div[@class=*]/a/h4" 

,或者如果你只希望那些特定的類,你可以嘗試:

@"//div[@class='info oeste']/a/h4 | //div[@class='info norte']/a/h4 | //div[@class='info centro']/a/h4" 

語法記錄here

+0

感謝這個完美的作品:) – MCKapur 2012-08-14 22:52:25