【问题标题】:Objective C Using NSScanner to obtain <body> from htmlObjective C 使用 NSScanner 从 html 中获取 <body>
【发布时间】:2015-03-28 01:39:06
【问题描述】:

我正在尝试创建一个 iOS 应用程序,只是为了提取网页的一部分。

我的代码可以连接到 URL 并将 HTML 存储在 NSString 中

我已经尝试过了,但我的结果只是得到空字符串

    NSScanner* newScanner = [NSScanner scannerWithString:htmlData];
    // Create a new scanner and give it the html data to parse.

    while (![newScanner isAtEnd])
    {
        [newScanner scanUpToString:@"<body>" intoString:NULL];
        // Scam until <body> tag is found

        [newScanner scanUpToString:@"</body>" intoString:&bodyText];
        // Everything up to the end tag will get placed into the memory address of the result string

    }

我已经尝试了另一种方法...

    NSScanner* newScanner = [NSScanner scannerWithString:htmlData];
    // Create a new scanner and give it the html data to parse.

    while (![newScanner isAtEnd])
    {
        [newScanner scanUpToString:@"<body" intoString:NULL];
        // Scam until <body> tag is found

        [newScanner scanUpToString:@">" intoString:NULL];
        // Go to end of opening <body> tag

        [newScanner scanUpToString:@"</body>" intoString:&bodyText];
        // Everything up to the end tag will get placed into the memory address of the result string

    }

第二种方式返回一个以&gt;&lt; script...等开头的字符串

如果我说实话,我没有一个好的 URL 来测试这个,我认为在删除正文中的标签方面也有一些帮助可能会更容易(比如 &lt;p&gt;&lt;/p&gt;

非常感谢任何帮助

【问题讨论】:

  • 你在哪里查看bodyText?在循环内还是之后?
  • 顺便说一下,如果您正在解析 HTML,您可能需要使用适当的解析器,例如 HPPL。例如,请参阅Ray Wenderlich's How to Parse HTML on iOS
  • 我在这个while循环之后检查了bodyText。我的具体任务是出于教育目的了解如何使用这些功能。我对 Objective C 和 iOS 很陌生,所以我只是想看看我能用这种方式做什么。在我了解了更基本的东西后,我会查看其他库

标签: html ios objective-c nsscanner


【解决方案1】:

我不知道为什么您的第一种方法不起作用。我假设您在该 sn-p 之前定义了 bodyText。这段代码对我来说很好用,

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *htmlData = @"This is some stuff before <body> this is the body </body> with some more stuff";
    NSScanner* newScanner = [NSScanner scannerWithString:htmlData];
    NSString *bodyText;
    while (![newScanner isAtEnd]) {
        [newScanner scanUpToString:@"<body>" intoString:NULL];
        [newScanner scanString:@"<body>" intoString:NULL];
        [newScanner scanUpToString:@"</body>" intoString:&bodyText];
    }
    NSLog(@"%@",bodyText); // 2015-01-28 15:58:00.360 ScanningOfHTMLProblem[1373:661934] this is the body 
}

请注意,我添加了对 scanString:intoString: 的调用以通过第一个 "&lt;body&gt;"

【讨论】:

  • 谢谢,所以我假设使用 scanUpToString 将在 标签之前停止。有没有一个很好的 URL 来测试这个问题?
  • @user3012508,是的,扫描仪将在该语句之后的正文中的“ 而不是 。所以你可能想扫描到“
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-07
  • 1970-01-01
  • 2016-04-13
  • 1970-01-01
相关资源
最近更新 更多