Ios

TFHpple解析htmlを使用したiOSデータ解析



Ios Data Parsing Using Tfhpple Parsing Html



TFHpple バックグラウンドから送信されたHTMLデータを解析するために使用できるXML / HTML解析フレームワークです。プロジェクトでこのフレームワークを使用する場合は、最初にフレームワークをインポートし、CocoaPodsを使用してここにインポートする必要があります。

以下はTFHppleのサンプルコードです。



#import 'TFHpple.h' NSData * data = [NSData dataWithContentsOfFile:@'index.html'] TFHpple * doc = [[TFHpple alloc] initWithHTMLData:data] NSArray * elements = [doc search:@'//a[@class='sponsor']'] TFHppleElement * element = [elements objectAtIndex:0] [e text] // The text inside the HTML element (the content of the first text node) [e tagName] // 'a' [e attributes] // NSDictionary of href, class, id, etc. [e objectForKey:@'href'] // Easy access to single attribute [e firstChildWithTagName:@'b'] // The first 'b' child node Copy code

HTMLのコンテンツを解析するには4つのステップがあることがわかります。

  • HTMLデータをNSDataタイプに変換する
  • データに基づいてTFHppleインスタンスを作成します
  • 配列内のノードを見つけます
  • 配列からノードを取り出します。

次に、TFHppleを使用して解析しますhttp://www.jianshu.com/u/b05772019513データで、各記事のタイトルを取得します。



コードは次のように表示されます。

NSString *url = @'http://www.jianshu.com/u/b05772019513' NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]] TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:data] NSArray *dataArr = [xpathParser searchWithXPathQuery:@'//a'] for (TFHppleElement *element in dataArr) { if ([[element objectForKey:@'class'] isEqualToString:@'title']) { NSLog(@'%@',element.text) } } Copy code

著者に連絡してください:ジェーンの本 DH_Fantasy 新浪微博・ DH_Fantasy 著作権表示:無料の再版-非営利-非派生-署名を保持( CC BY-NC-ND 3.0 )。

転載:https://juejin.im/post/5a9021e451882518c0797f6f