1. 程式人生 > >萬方資料知識平臺 TFHpple +Xpath解析

萬方資料知識平臺 TFHpple +Xpath解析

試了一下,基本上適合所有的檢索結果。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //獲取資料
    NSURL *url=[NSURL URLWithString:@"http://s.g.wanfangdata.com.cn/Paper.aspx?q=hiv"];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    //解析資料
    TFHpple *hpple=[TFHpple hppleWithHTMLData:data];
    
    //XPATH字串 越短越好,但是要能過濾出符合要求的結果
    //xpath教程:http://www.w3cschool.cn/index-14.html
    NSString *xpathStr 
[email protected]
"//div/ul/li [@class='title_li'] /a [not(@class)]";//解析標題 NSString *xpathStr2 [email protected]"//div/ul/li [@class='zi'] ";//解析簡介 NSArray *arr=[hpple searchWithXPathQuery:xpathStr]; NSArray *arr2=[hpple searchWithXPathQuery:xpathStr2]; //NSLog(@"%@",arr2); //這個陣列中就有需要的值 alltilte=[[NSMutableArray alloc]init]; alltext=[[NSMutableArray alloc]init]; alltilte = [self SaveArry:arr]; alltext = [self SaveAlltext:arr2]; for(int i=0;i<alltilte.count;i++) { NSLog(@"標題%@",alltilte[i]); NSLog(@"簡介%@",alltext[i]); } [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"]; } -(NSMutableArray *)SaveAlltext :(NSArray *)_arry { for (TFHppleElement *tmp in _arry) { NSString * string =[tmp raw]; NSRange range; // NSRange range2; range = [string rangeOfString:@"<br />"]; string = [string substringToIndex:range.location]; NSString *temp =[string stringByReplacingOccurrencesOfString:@"<li class=\"zi\"> " withString:@""]; temp =[temp stringByReplacingOccurrencesOfString:@"<font color=\"red\">" withString:@""]; temp =[temp stringByReplacingOccurrencesOfString:@"</font>" withString:@""]; temp =[temp stringByReplacingOccurrencesOfString:@"<li class=\"zi\">" withString:@""]; [alltext addObject:temp]; } return alltext; } -(NSMutableArray *)SaveArry: (NSArray *)_arry { for (TFHppleElement *tmp in _arry) { NSString * string =[tmp raw]; NSRange range; NSRange range2; range = [string rangeOfString:@"</a>"]; string = [string substringToIndex:range.location]; NSString *temp =[string stringByReplacingOccurrencesOfString:@"<font color=\"red\">" withString:@""]; temp=[temp stringByReplacingOccurrencesOfString:@"</font>" withString:@""]; range = [string rangeOfString:@">"]; range2 = [string rangeOfString:@"img"]; if(range.length!=0&&range2.length==0) { string = [temp substringFromIndex:range.location+1]; [alltilte addObject:string]; } } return alltilte; }