【问题标题】:How to parse HTML sub tags in iPhone app?如何在 iPhone 应用程序中解析 HTML 子标签?
【发布时间】:2023-04-06 01:59:01
【问题描述】:

我有很多图片和实时内容的 HTML 网页。我需要parse the data from the webpage(HTML) 并在 iPhone 应用程序中显示。我正在使用以下代码来解析 HTML 内容。但是不知道怎么解析标签里的子标签?

{    
    NSURL *url = [NSURL URLWithString:@"http://www.samplewebpage.com/vd/t/1/830.html"]; 

    NSData *data = [[NSData alloc] initWithContentsOfURL:url];
    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"Response : %@", responseString);

    NSMutableArray *imageURLArray = [[NSMutableArray alloc] init];
    NSMutableArray *divClassArray = [[NSMutableArray alloc] init];
    //NSString *regexStr = @"<A HREF=\"([^>]*)\">";

    // For image : 1. img src=\"([^>]*)\"  2. <img src=\"([^>]*)\">
    // For getting Class div class
    NSString *regularExpressString = @"div class=\"([^>]*)\"";
    NSError *error;
    NSInteger i =0;
    while (i<[responseString length]) 
    {
        NSRegularExpression *testRegularExpress = [NSRegularExpression regularExpressionWithPattern:regularExpressString options:NSRegularExpressionCaseInsensitive error:&error];

        if( testRegularExpress == nil ) 
        {
            NSLog( @"Error making regex: %@", error );
        }

        NSTextCheckingResult *textCheckingResult = [testRegularExpress firstMatchInString:responseString options:0 range:NSMakeRange(i, [responseString length]-i)];
        NSRange range = [textCheckingResult rangeAtIndex:1];
        if (range.location == 0) 
        { 
            break;
        }
        NSString *classNameString = [responseString substringWithRange:range];
        NSLog(@"Div Class Name : %@", classNameString);

        [divClassArray addObject:classNameString];

        i= range.location;
        //NSLog(@"Range.location : %i",range.location);
        i=i+range.length;
    }

    NSLog(@"divClass Array : %@, Count : %d", divClassArray, [divClassArray count]);
}

回复:

<div class="phoneModelItems" style="width:30%;margin-right:4px;"><a href="javascript:noxLatestChart.navToLatestChart('latest');" style="font-weight:italic;">Nokia Model</a></div>

我想从 phoneModelItems 类中获取文本 Nokia Model。你能告诉我如何检索文本“诺基亚模型”吗?提前致谢。

【问题讨论】:

  • 你能把responseString贴出来
  • 麦肯先生感谢您的回复。我已经编辑了这个问题。我已经提到了回应。你能帮我么?谢谢。
  • @Gopinath 你找到解决方案了吗?

标签: iphone html ios tags html-parser


【解决方案1】:

这是我针对您的问题的正则表达式:

<div\sclass=\"phoneModelItems\".*?><a\shref.*?>(.*?)<\/a><\/div>

你可以在Rubular上测试它

【讨论】:

  • 谢谢麦肯先生。我会在我的项目中尝试。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2012-06-06
  • 2011-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 2012-08-03
相关资源
最近更新 更多