我已经按照 RayWendErlich 中的教程进行操作解析 HTML 节点。
我从 index.html
中获取内容。
我尝试使用此方法来获取 background 值。
+ (void)parseWithHTMLString:(NSString *)string
{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
TFHpple *parser = [TFHpple hppleWithData:data isXML:NO];
NSString *XpathQueryString = @"//div[class='content']/div/div";
NSArray *nodes = [parser searchWithXPathQuery:XpathQueryString];
NSLog(@"%@",nodes);
NSMutableArray *resultArray = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in nodes) {
Model *model = [[Model alloc] init];
model.colorString = [element objectForKey:@"style"];
[resultArray addObject:model];
//NSLog(@"%@",model.colorString);
}
}
那么问题是:
我做错了什么?
最佳答案
您的代码中有 2 个小错误。
- 您使用的 xPath 不正确。您在
class
前面缺少一个@
。 background
键是一个属性,因此您需要向TFHppleElement
询问其attributes
属性(这是一个字典)并获取它的值通过objectForKey:
。
这是最终代码:
NSArray *nodes = [parser searchWithXPathQuery:@"//div[@class='content']/div/div"];
for (TFHppleElement *element in nodes) {
NSLog(@"%@",[element.attributes objectForKey:@"style"]);
}
控制台输出为:
background: #D93D59
background: #E7923D
background: #768479
background: #EBBA95
background: #E26967
background: #BF343F
background: #254159
background: #F2F2F2
background: #D9A577
background: #BF8969
background: #04000D
...
关于html - Hpple 使用 Objective-C 解析 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27468087/