【问题标题】:Hpple parsing HTML with Objective-CHpple 使用 Objective-C 解析 HTML
【发布时间】:2015-02-12 14:34:12
【问题描述】:

我已经按照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);
  }
}

所以问题是:

我做错了什么?

【问题讨论】:

  • 它是做什么的,你希望它做什么?
  • 当你运行你拥有的代码时,你得到了吗?如果我们不知道出了什么问题,我们将无法帮助您。我猜您使用了错误的 xpath,但由于您没有向我们展示 html 代码,因此我们无法帮助您。
  • 你试过model.colorString = [element.attributes objectForKey:@"style"];
  • @HAS 立即尝试,什么都没有。我打印了nodes 变量,该变量控制台将Nodes was nil 返回给我。也许是问题。

标签: html ios objective-c xpath hpple


【解决方案1】:

您的代码中有 2 个小错误。

  1. 您使用的 xPath 不正确。您在 class 前面缺少一个 @。
  2. background 键是一个属性,因此您需要向TFHppleElement 询问其attributes 属性(这是一个字典)并通过objectForKey: 获取其值。

这是最终代码:

NSArray *nodes = [parser searchWithXPathQuery:@"//div[@class='content']/div/div"];

for (TFHppleElement *element in nodes) {
    NSLog(@"%@",[element.attributes objectForKey:@"style"]);
}

控制台输出为:

背景:#D93D59
背景:#E7923D
背景:#768479
背景:#EBBA95
背景:#E26967
背景:#BF343F
背景:#254159
背景:#F2F2F2
背景:#D9A577
背景:#BF8969
背景:#04000D
...

【讨论】:

    猜你喜欢
    • 2013-04-15
    • 2015-09-27
    • 2012-08-24
    • 2013-02-17
    • 2011-05-21
    • 1970-01-01
    • 2011-02-21
    • 2012-08-10
    • 1970-01-01
    相关资源
    最近更新 更多