2017-08-01 41 views
0

这里是我的代码示例:NSURLSession如何检索只有标题?

- (void)displayURL { 

    NSString *myUrlString = @"https://3docean.net/search/apple%20watch?page=1"; 
    NSURL *myUrl = [NSURL URLWithString:myUrlString]; 
    NSURLSession *session = [NSURLSession sharedSession]; 

    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:myUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
     if (!error) { 
      NSString *htmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
      NSLog(@"%@", htmlString); 

     } else { 
      NSLog(@"error = %@", error.localizedDescription); 
     } 
    }]; 
    [dataTask resume]; 
} 

它返回:

data structure

我想要检索和NSLog只有所有的标题。

+0

你可以尝试一个HTML解析器(有几个库)或'NSRegularExpression'和基准两种解决方案。 – nathan

+0

看看这个:https://www.raywenderlich.com/14172/how-to-parse-html-on-ios。这可能会帮助你 – 3stud1ant3

+0

如果该网站的Web API以XML或JSON响应,我显然会更好。否则,它只是更多的自定义/复杂的解析,如果他们更改页面的HTML代码,您可能需要重做它。 – Larme

回答

1

尝试下面的代码,你会得到你想要的输出。

NSString *myUrlString = @"https://3docean.net/search/apple%20watch?page=1"; 
NSURL *myUrl = [NSURL URLWithString:myUrlString]; 
NSURLSession *session = [NSURLSession sharedSession]; 

NSURLSessionDataTask *dataTask = [session dataTaskWithURL:myUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    NSString *htmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@", htmlString); 

    NSArray *urlComponents = [htmlString componentsSeparatedByString:@"title="]; 

    NSMutableArray *arrTitles = [[NSMutableArray alloc]init]; 
    for (NSString *str in urlComponents) 
    { 
     NSString* newNSString =[[[[str componentsSeparatedByString:@"\""]objectAtIndex:1] componentsSeparatedByString:@"\""]objectAtIndex:0]; 

     [arrTitles addObject:newNSString]; 
    } 

    NSLog(@"arrTitles : %@",arrTitles); 

}]; 
[dataTask resume]; 

这是我的输出,其中包含所有“标题”值。

enter image description here

+0

这是非常肮脏的解决方案,但它的工作原理。谢谢。 我只是说,而不是 “的NSLog” 这个代码行: “为(在arrTitles的NSString *标题){ 如果([标题rangeOfString:@” 苹果观察“。位置== NSNotFound){ }其他{ [titleWatches addObject:title]; } }“ 现在它只输出需要的标题。 –