以下是我的代码示例:
- (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];
}
它返回:
我想检索并NSLog
只有所有标题。
答案 0 :(得分: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];
这是我的输出,其中包含所有"标题"值。