【问题标题】:Simplest way to parse html tag objective c解析html标签目标c的最简单方法
【发布时间】:2015-07-11 02:44:10
【问题描述】:

在我的一个 ios 项目中,我将 img 标签作为图像的 url。现在我必须从 img 标签中获取 href。

什么是最好和最简单的解决方案。

这是我从结果中得到的结果

<img src=\"http://www.shareatalent.com/wp-content/uploads/avatars/103533/103533-bpfull.jpg\" class=\"avatar user-103533-avatar avatar-450 photo\" width=\"450\" height=\"450\" alt=\"Profile photo of sb\" />

结果应该是

http://www.shareatalent.com/wp-content/uploads/avatars/103533/103533-bpfull.jpg

【问题讨论】:

  • 使用 NSRegularExpression
  • 使用 TFHpple。更多信息:how-to-parse-html-on-ios,Thomas Kilian 的想法要好得多,因为您不必导入文件,因为您只解析单个元素。
  • Objective-C-HMTL-Parser 是用于解析 HTML 文本的包装类,可能会对您有所帮助。

标签: html ios objective-c html-parsing


【解决方案1】:

将此库 https://github.com/volodg/HTMLParser 添加到您的项目中,并将 libxml2 和 libxml2.2 添加到您的项目中,然后将其添加到您的解析操作(例如按钮操作):

#import "HTMLparser.h"
 NSError *error = nil;
NSString *html = @"<img src=\"http://www.shareatalent.com/wp-content/uploads/avatars/103533/103533-bpfull.jpg\" class=\"avatar user-103533-avatar avatar-450 photo\" width=\"450\" height=\"450\" alt=\"Profile photo of sb\" />
";
HTMLParser *parser = [[HTMLParser alloc] initWithString:html error:&error];

if (error) {
    NSLog(@"Error: %@", error);
    return;
}

HTMLNode *bodyNode = [parser body];


NSArray *spanNodes = [bodyNode findChildTags:@"img"];

for (HTMLNode *spanNode in spanNodes) {
    if ([[spanNode getAttributeNamed:@"class"] isEqualToString:@"avatar user-103533-avatar avatar-450 photo"]) {
        NSLog(@"%@", [spanNode getAttributeNamed:@"src"]); //Gives The Image URL
    }
}

【讨论】:

【解决方案2】:

HTML 转换为NSAttributeString 时有很多功能。但我会建议帮助您完成基本功能的教程,如颜色更改、字体更改、添加链接、添加内嵌图像。

Convert HTML string to NSAttributeString

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多